문제

I am developing an android app for some specific use, and this app uses the webview to load URL's. I need to determine the request type of the URL i.e. if it is a GET, POST or DELETE request type. I tried using getMethod in java, but not very sure how to use it as I am a newbie to Java.

Thanks!

도움이 되었습니까?

해결책

URLs don't have types. HTTP requests to a URL do, though. In this answer, I assume that's what you're talking about.

In the standard JRE, you make HTTP requests using a URLConnection. If you know you're making an HTTP request using URL#openConnection(), you can cast the result of that method to an http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html. That getRequestMethod() method that will give you the type of the HTTP request method.

For example:

URL url=new URL("http://www.google.com/");
HttpURLConnection cn=(HttpURLConnection) url.openConnection();

// Configure URLConnection here...
cn.setRequestMethod("POST");            // Use a POST request
cn.setDoOutput(true);                   // We'll send a request body
OutputStream body=cn.getOutputStream(); // Send our output...
try {
    // Do output...
}
finally {
    body.close();
}
InputStream response=cn.getInputStream();
try {
    // Get our request method
    String requestMethod=cn.getRequestMethod();            // POST
    Map<String,List<String>> headers=cn.getHeaderFields(); // Check other response headers

    // Handle input...
}
finally {
    response.close();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top