Я пытаюсь сделать POST-запрос с использованием андроид 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. Не могли бы вы мне помочь, что не так?
Er ... на какой строке он бросает 'IOException' ?! –
On 'is = conn.getInputStream();' –