2011-06-30 27 views
10

我正在使用下面的代碼來做一個httpPost調用,但它返回給我400個不好的請求 當我嘗試在Chrome擴展中的「簡單的休息客戶端」提供以下參數它工作正常任何人指導我我在這裏做什麼錯誤?如何使用json編碼體進行httpPost調用?

簡單的REST客戶端我進了以下內容:

網址:http://jon2012.com/api/register 方法:POST 頭:沒有頭部的,因爲他們並不需要 數據:{ 「電子郵件」: 「[email protected]」 「FIRST_NAME」: 「姓名」} enter image description here

的Android代碼:

HttpClient client = new DefaultHttpClient(); 
     HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit 
     HttpResponse response; 
     JSONObject json = new JSONObject(); 
     try{ 
      HttpPost post = new HttpPost(url); 
      json.put("email", email); 
      json.put("first_name", name); 
      StringEntity se = new StringEntity("JSON: " + json.toString()); 
      se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
      post.setEntity(se); 
      response = client.execute(post); 
      /*Checking response */ 
      /*if(response!=null){ 
       InputStream in = response.getEntity().getContent(); //Get the data in the entity 
*/ 
      int statusCode = response.getStatusLine().getStatusCode(); 

     } 
     catch(Exception e){ 
      e.printStackTrace(); 
      // createDialog("Error", "Cannot Estabilish Connection"); 
     } 

任何幫助將appriciated

+0

是您的JSON數據模式是相同要求的服務? –

回答

21

我正在犯一個常見的錯誤序列的JSON對象是錯誤的。 例如我會發送它像 FIRST_NAME,email..etc..where爲正確序列電子郵件,FIRST_NAME

我的代碼

boolean result = false; 
     HttpClient hc = new DefaultHttpClient(); 
     String message; 

     HttpPost p = new HttpPost(url); 
     JSONObject object = new JSONObject(); 
     try { 

      object.put("updates", updates); 
      object.put("mobile", mobile); 
      object.put("last_name", lastname); 
      object.put("first_name", firstname); 
      object.put("email", email); 

     } catch (Exception ex) { 

     } 

     try { 
     message = object.toString(); 


     p.setEntity(new StringEntity(message, "UTF8")); 
     p.setHeader("Content-type", "application/json"); 
      HttpResponse resp = hc.execute(p); 
      if (resp != null) { 
       if (resp.getStatusLine().getStatusCode() == 204) 
        result = true; 
      } 

      Log.d("Status line", "" + resp.getStatusLine().getStatusCode()); 
     } catch (Exception e) { 
      e.printStackTrace(); 

     } 

     return result; 
+22

添加參數的順序應該完全沒有區別。接收參數的Web服務器不應該關心參數的順序,只是參數嵌套正確並且鍵被正確定義 – jamesc

+16

我不確定這是如何正確的答案......並且已經被四個人投票了人。 JSON參數的順序無關緊要。 –

0

這是我與HTTP POST和JSON調用REST服務代碼:

(請注意,我使用AndroidHttpClient,這基本上是與一些預設屬性的DefaultHttpClient,以及谷歌的GSON項目JSON編組)

類處理通信:

public class NetworkComm extends AsyncTask<String, Integer, String> { 

    // Log tag 
    private static final String TAG = "NetworkComm"; 

    private AndroidHttpClient hc; 
    private HttpContext localContext; 
    private TaskResponseListener listener; 
    private int reqType; 
    private String message; 
    private String url; 
    private Object extra; 

    public NetworkComm(AndroidHttpClient hc, HttpContext localContext, TaskResponseListener listener, 
      int reqType, String message, String url, Object extra){ 
     super(); 

     this.hc = hc; 
     this.localContext = localContext; 
     this.listener = listener; 
     this.reqType = reqType; 
     this.message = message; 
     this.url = url; 
     this.extra = extra; 
    } 

    public AndroidHttpClient getHc() { 
     return hc; 
    } 

    public void setHc(AndroidHttpClient hc) { 
     this.hc = hc; 
    } 

    public HttpContext getLocalContext() { 
     return localContext; 
    } 

    public void setLocalContext(HttpContext localContext) { 
     this.localContext = localContext; 
    } 

    public void start(){ 
     this.execute(message); 
    } 

    protected void onPreExecute() { 
     //Don't do anything here 
    } 

    protected String doInBackground(String... req) { 

     Log.d(TAG, "Message to send: "+req[0]); 
     HttpPost p = new HttpPost(url); 

     try{ 
      p.setEntity(new StringEntity(req[0], "UTF8")); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
     p.setHeader("Content-type", "application/json"); 

     String response = ""; 
     try{ 
      HttpResponse resp = hc.execute(p, localContext); 
      InputStream is = resp.getEntity().getContent(); 
      response = convertStreamToString(is); 
      Log.d("Response", "Response is " + response); 

      Log.d("Status line", ""+resp.getStatusLine().getStatusCode()); 
     } catch (Exception e){ 
      e.printStackTrace(); 
     } 

     return response; 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     // dont handle this yet 
    } 

    @Override 
    protected void onCancelled() { 
     super.onCancelled(); 
    } 

    protected void onPostExecute(String result) { 
     Log.d("task", "task finished"); 
     listener.onTaskResponse(reqType, result, extra); 
    } 

    public interface TaskResponseListener{ 
     public void onTaskResponse(int type, String response, Object extra); 
    } 

    private String convertStreamToString(InputStream is) throws IOException { 
     if (is != null) { 
      Writer writer = new StringWriter(); 

      char[] buffer = new char[1024]; 
      try { 
       Reader reader = new BufferedReader(
         new InputStreamReader(is, "UTF-8")); 
       int n; 
       while ((n = reader.read(buffer)) != -1) { 
        writer.write(buffer, 0, n); 
       } 
      } finally { 
       is.close(); 
      } 
      return writer.toString(); 
     } else {   
      return ""; 
     } 
    } 
} 

用法:

Gson g = new Gson(); 
     SomeContent content = new SomeContent("Stuff", 4); 
     String message = g.toJson(content); 

     NetworkComm task = new NetworkComm(hc, localContext, listener, 0, message, url, ""); 
     task.start(); 

希望這有助於。

+0

我想發送兩個參數電子郵件和名字,請你指導我在哪裏使用它們? – UMAR

+0

什麼是Gson?什麼是SomeContent實際上這是令人困惑的部分 – UMAR

+0

SomeContent是一些內容:)一個自定義類,其中包含您想要發送的數據的字段。 Gson被用來把它放到json中,將它們進行谷歌搜索,它比android sdk中的默認json庫更方便,更易於使用。 –