【发布时间】:2014-09-06 20:11:01
【问题描述】:
我正在尝试使用 android HttpUrlConnection 发出 POST 请求。首先,我使用此处的 GET 请求示例:
http://developer.android.com/training/basics/network-ops/connecting.html#http-client
它运行良好(例如我得到 google.com 页面)。然后我进行一些更改以发出 POST 请求:更改 POST 上的请求方法:
conn.setRequestMethod("POST");
并添加此代码(从此处获取:http://developer.android.com/reference/java/net/HttpURLConnection.html):
conn.setDoOutput(true);
conn.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.close();
所以现在方法 downloadUrl 看起来像这样:
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.close();
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
而且它总是抛出 IOException。你能帮我看看有什么问题吗?
【问题讨论】:
-
呃...它在哪一行抛出
IOException?! -
开启
is = conn.getInputStream();
标签: java android http-post httpurlconnection