如Android文档所示,我已设置setDoOutPut(true);
,以便连接以POST
的形式发送。但是,在检查HTTPURLConnection
方法成员时,在调试器中,即使在setDoOutput(true)甚至GET
之后,它始终为setRequestMethod("POST")
。我是以某种方式将其重置为GET
?
URL url = new URL(serverAddr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod(verb);
urlConnection.setFixedLengthStreamingMode(postBody.getBytes().length);
//urlConnection.setRequestProperty("Content-Length", postBody.getBytes().toString());
urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
urlConnection.connect();
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(postBody.getBytes());
out.flush();
int responseCode = urlConnection.getResponseCode();
System.out.println("HTTPS RESPONSE CODE: " + responseCode);
out.close();
编辑:这必须是一个错误...调试器显然将setDoOuput成员变量显示为false,即使我将其设置为true也是如此。它没有被设定!
答案 0 :(得分:0)
如果您希望使用POST动词并根据请求发送数据,则需要使用urlConnection.setDoInput(true);
。
http://developer.android.com/reference/java/net/URLConnection.html#setDoInput(boolean)
必须在建立连接之前设置。
答案 1 :(得分:0)
这是我的工作范例:
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
Map<String, List<String>> mp = conn.getHeaderFields();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}