Я пытаюсь отправить HTTP-запрос. В настоящее время я застрял на добавление Content-Length собственности: У меня естьКакое значение следует использовать для Content-Length HTTP-запроса POST?
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.addHeader("Content-Length", ""+json.length());
Если я комментировать последнюю строку (Content-Length) сервер возвращает мне ошибку, что я скучаю л я последняя строка остается раскомментировала - тогда я ловлю исключение при попытке сделать
HttpResponse httpResponse = httpclient.execute(httpPost);
Пожалуйста, скажите мне, что я делаю неправильно с настройкой заголовков.
PS Я посылаю простой объект JSON
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("phone", phone);
Мой полный фрагмент кода после Metod:
public static JSONObject POST(String url, String phone){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
Log.d("ANT", "JSONObject jsonObject = new JSONObject(); PHONE:"+phone);
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("phone", phone);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
Log.d("ANT", "json"+json.length());
// 7. Set some headers to inform server about the type of the content
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;");
// httpPost.addHeader("Content-Length", ""+json.length());
// 8. Execute POST request to the given URL
Log.d("ANT", "httpPost:"+getStringFromInputStream(httpPost.getEntity().getContent()));
for (Header s : httpPost.getAllHeaders())
Log.i("ANT", "header::"+s.getName() + ":"+s.getValue());
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
Log.d("ANT", "httpResponse.getEntity().getContent();");
// 10. convert inputstream to string
if (inputStream != null) {
result = getStringFromInputStream(inputStream);
Log.d("ANT", "getStringFromInputStream : "+result);
JSONObject obj = new JSONObject(result);
Log.d("ANT", "JSONObject");
return obj;
}
else
result = "Did not work!";
} catch (ClientProtocolException e) {
Log.d("ANT", "ClientProtocolException : "+ e.getLocalizedMessage());
} catch (IOException e) {
Log.d("ANT", "IOException:"+ e.getLocalizedMessage());
} catch (Exception e) {
Log.d("ANT", "Exception:"+ e.getLocalizedMessage());
}
// 11. return result
return null;
}
У меня есть ClientProtocolException с e.getLocalizedMessage(): null; if httpPost.addHeader ("Content-Length", "" + json.length()); без ранения. Если он заработал, сервер дает «: -31», «Сообщение»: «Операция запрещена. Пожалуйста, свяжитесь с нами » –
Можете ли вы показать фрагмент кода, как формировать почтовый запрос? Кроме того, json.length() возвращает sth больше 0? Кроме того, вы также можете попробовать проверить с помощью tcpdump или wireshark, если запрос, который вы отправляете на самом деле содержит корректные данные заголовка и содержимого. – fishi
json.length() возвращает 24 на самом деле. Будет добавлен минутный код –