0

I'm looking at the documentation here: http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html

I'm not seeing an option to flag a request as a POST method. I'd expect to see .setRequestMethod("POST"); or something. Am I looking at the wrong documentation?

I'm using Android 4.2 and Java 1.6. Though I'm unsure if javase/1.4.2 is what I should be looking for.

URL url = new URL(this.getUrl());
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
4

2 回答 2

1

您需要使用HTTPURLConnection而不是URLConnection

HTTPURLConnection 有setRequestMethod

例子:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

注意:最好使用最新的 javadoc 而不是旧版本,1.4 是相当旧的 java 版本。

归功于 Luigi R. Viggiano :

我上面的回答只涉及如何访问setRequestMethod. 如果您不想使用 setRequestMethod,而是按照 Luigi 的建议实现 POST,则可以忽略调用 setRequestMethod,只需 set即可setDoOutput(true)。阅读本教程以获取更多信息。

于 2012-12-31T16:44:51.410 回答
0

你可以使用这个,你已经有了比我发布的更多的选择

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLIS);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLIS);
HttpClient client = new DefaultHttpClient(httpParams);

HttpUriRequest request = new HttpPost(serverUrl);
于 2012-12-31T16:53:20.370 回答