我试图做一个POST请求使用android HttpUrlConnection。首先,我用的例子为GET请求从这里:HttpURLConnection POST请求抛出IOException
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' ?!! – 2014-09-06 20:13:04
On'is = conn.getInputStream();' – 2014-09-06 20:17:31