2015-01-25 2 views
0

Я пытаюсь отправить 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; 
    } 

ответ

3

Вы можете уточнить, что код ошибки сервера и трассировки стека, когда исключение имеет место?

Edit:

Я попробовал какую-то часть вашего кода. Я не ставил Content-Length (так как это должно быть сделано автоматически):

public class App 
{ 
    public static void main(String[] args) 
    { 
     post("http://www.baidu.com","+8912345"); 
    } 

    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 
      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); 

      // 7. Set some headers to inform server about the type of the content 
      httpPost.addHeader("Accept", "application/json"); 
      httpPost.addHeader("Content-Type", "application/json;"); 

      // 8. Execute 
      HttpResponse httpResponse = httpclient.execute(httpPost); 

      // 9. receive response as inputStream 
      inputStream = httpResponse.getEntity().getContent(); 

     } catch (ClientProtocolException e) { 
      System.out.println("ClientProtocolException : "+e.getLocalizedMessage()); 
     } catch (IOException e) { 
      System.out.println("IOException:"+ e.getLocalizedMessage()); 
     } catch (Exception e) { 
      System.out.println("Exception:"+ e.getLocalizedMessage()); 
     } 

     return null; 
    } 
} 

я использовал Wireshark и может подтвердить, что следующий запрос будет Baidu:

POST/HTTP/1.1
Принять: применение/json
Content-Type: application/json;
Content-Length: 20
Хост: www.baidu.com
соединения: Keep-Alive
User-Agent: Apache-HttpClient/4.3.6 (Java 1.5)

{ "телефон":» +8912345 "}

Это показывает, что запрос отправлен должным образом, что означает, что клиентская сторона выглядит нормально. Вот почему я бы предложил проверить серверную сторону на наличие ошибок. Как я уже говорил, я думаю, вы должны использовать tcpdump или wirehark для проверки трафика между клиентом и сервером. Это может дать вам лучшее представление о том, что происходит не так.

+0

У меня есть ClientProtocolException с e.getLocalizedMessage(): null; if httpPost.addHeader ("Content-Length", "" + json.length()); без ранения. Если он заработал, сервер дает «: -31», «Сообщение»: «Операция запрещена. Пожалуйста, свяжитесь с нами » –

+0

Можете ли вы показать фрагмент кода, как формировать почтовый запрос? Кроме того, json.length() возвращает sth больше 0? Кроме того, вы также можете попробовать проверить с помощью tcpdump или wireshark, если запрос, который вы отправляете на самом деле содержит корректные данные заголовка и содержимого. – fishi

+0

json.length() возвращает 24 на самом деле. Будет добавлен минутный код –

Смежные вопросы