2012-03-27 47 views
0

我試圖執行一個POST請求到一個服務器,希望內容類型設置爲應用程序/ json的名稱和電子郵件作爲一些鍵。目前,我得到了一個406錯誤,我假設在服務器端工作,但android無法處理響應。我如何調整代碼以獲得200響應?這個POST請求與Android上的JSON有什麼不對?

HttpClient client = new DefaultHttpClient(); 
HttpEntity entity; 

try{ 
    JSONObject j = new JSONObject(); 
    j.put("name" , myName); 
    j.put("email", myEmail); 

    HttpPost post = new HttpPost(targetURL); 
    post.setHeader("Content-Type", "application/json"); 

    StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8); 
    se.setContentType("application/json"); 
    post.setEntity(se); 

    HttpResponse response = client.execute(post); 
    entity = response.getEntity(); 

    Log.d("response", response.getStatusLine().toString()); 
} catch(Exception e){Log.e("exception", e.toString());} 

這是否看起來正確?創建HttpClient時是否需要其中一個響應處理程序?

+0

你發佈什麼服務器?你是否控制它,或者有它的代碼?你能檢查服務器接收到什麼嗎?如果您無法訪問服務器和/或其代碼,則可能需要在開發機器上設置Tomcat實例並進行測試。 – 2012-03-27 18:12:31

+0

是JSON密鑰名稱是否正確?有沒有額外的標題你應該發送? – dldnh 2012-03-27 18:17:18

+0

不幸的是,我沒有訪問服務器。我也不知道是否需要發送其他頭文件(比如這個接受頭文件) – nectarsac 2012-03-27 20:21:15

回答

0

這對我的作品與JSON-2.0.jar

 HttpClient client = new DefaultHttpClient(); 
     HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit 
     HttpResponse response; 
     ArrayList<appResults> arrayList = new ArrayList<appResults>(); 
     String resul; 
     try{ 

      HttpGet get = new HttpGet(urls[0]); 


      response = client.execute(get); 
      /*Checking response */ 
      if(response!=null){ 
       InputStream in = response.getEntity().getContent(); //Get the data in the entity 
       resul = convertStreamToString(in); 
       Gson gson = new Gson();     
       Type listType = new TypeToken<ArrayList<appResults>>() {}.getType(); 
       arrayList = gson.fromJson(resul, listType); 
       in.close(); 
當然在的AsyncTask或線程

。 但406 ...似乎你的網絡服務器和你的應用程序的格式不一致...

+0

不管'converStreamToString()'做什麼,它都是不正確的。請使用[EntityUtils.toString(response.getEntity())](http://developer.android.com/reference/org/apache/http/util/EntityUtils.html#toString(org.apache.http.HttpEntity))因爲它更少的代碼並服從服務器發送的字符編碼。 – 2012-03-27 18:14:37

+0

唯一的是你正在執行獲取請求。我應該把它切換到HttpPost嗎? – nectarsac 2012-03-27 20:20:37