Запросы HttpURLConnection, HttpClient и HttpPost не работают с запросом POST в Android
Я пробовал много разных способов получить http ответ, но всегда получаю сообщение ноль. Я попытался с помощью инструмента Advance Rest Client, который поставляется с Chrome. В этом я получаю ответ с успехом. Я не знаю, где я делаю неправильно.
try {
String urlParameters = "id=userid&password=password&device=android";
URL url = new URL("my url");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
urlConnection.setRequestProperty("Content-Language", "en-US");
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(urlParameters.getBytes());
outputStream.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = urlConnection.getInputStream();
resultstring = convertinputStreamToString(in);
Log.d("Result String-------->", resultstring);
}
} catch (Exception e) {
e.printStackTrace();
}
Я приложил скриншот, где я получаю результат: успех Но в приведенном выше коде я получаю результат: сбой
Я также пробовал код с использованием HttpClient и HttpPost. Но это также работает
try {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"my url");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("id", "userid"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
nameValuePairs.add(new BasicNameValuePair("device", "android"));
// httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
UrlEncodedFormEntity se = new UrlEncodedFormEntity(nameValuePairs);
se.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(se);
httpPost.getParams().setBooleanParameter(
"http.protocol.expect-continue", false);
HttpResponse response = client.execute(httpPost);
String responseAsText = EntityUtils.toString(response.getEntity());
Log.d("Result String-------->", responseAsText);
} catch (Exception e) {
e.printStackTrace();
}
Пожалуйста, помогите мне. Я перепробовал почти все.
1 ответ
HttpClient localHttpClient = this.app2.getHttpClient();
HttpPost localHttpPost = new HttpPost("yourURL.com");
localHttpPost.setEntity(new UrlEncodedFormEntity(myArrayList));
InputStream localInputStream = localHttpClient.execute(localHttpPost).getEntity().getContent();
Попробуйте что-то вроде этого. Вы должны прочитать ответ как входной поток и затем выполнить свою работу после того, как результат будет возвращен.
также обязательно проверьте сервер, так как он может не возвращать ответ, как ожидалось.