-4

我正在为某些特定用途开发一个 android 应用程序,这个应用程序使用 webview 来加载 URL。我需要确定 URL 的请求类型,即它是 GET、POST 还是 DELETE 请求类型。我尝试在 java 中使用 getMethod,但不太确定如何使用它,因为我是 Java 新手。

谢谢!

4

1 回答 1

3

URL 没有类型。不过,对URL 的HTTP 请求确实如此。在这个答案中,我认为这就是您所说的。

在标准 JRE 中,您使用URLConnection发出 HTTP 请求。如果您知道您正在使用URL#openConnection()发出 HTTP 请求,则可以将该方法的结果转换为 http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection .html。该getRequestMethod()方法将为您提供 HTTP 请求方法的类型。

例如:

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();
}
于 2013-06-27T02:40:07.547 回答