2013-01-22 148 views
1

我正在做一個Android應用程序,並且對我自己的服務器執行我的請求時遇到問題。我已經使用Play Framework的服務器,並從Json獲取參數:當我對我的服務器發出GET請求時,一切正常。但是當我發出一個POST請求時,我的服務器返回了一個未知的錯誤,關於有一個格式不正確的JSON或者它無法找到該元素。Android請求中的發佈參數

private ArrayList NameValuePair> params;

private ArrayList NameValuePair> headers;

...

情況下POST:

HttpPost postRequest = new HttpPost(host); 
    // Add headers 
    for(NameValuePair h : headers) 
    { 
     postRequest.addHeader(h.getName(), h.getValue()); 
    } 
    if(!params.isEmpty()) 
    { 
     postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
    } 
    executeRequest(postRequest, host); 
    break; 

我曾嘗試與請求的PARAMS做的,但它是一個失敗:

如果(! params.isEmpty()) {
HttpParams HttpParams = new BasicHttpParams();

for (NameValuePair param : params) 
{ 
     HttpParams.setParameter(param.getName(), param.getValue()); 
}     
postRequest.setParams(HttpParams); } 

而且還有不同的錯誤,取決於我做的請求。他們都是 'play.exceptions.JavaExecutionException':

  • 'com.google.gson.stream.MalformedJsonException'
  • '這不是一個JSON對象'
  • 「要求對象中找到:「ID 「'

我希望有人能幫助我。

回答

3

以下是發送HTTP Post的簡單方法。

HttpPost httppost = new HttpPost("Your URL here"); 
httppost.setEntity(new StringEntity(paramsJson)); 
httppost.addHeader("content-type", "application/json"); 
HttpResponse response = httpclient.execute(httppost); 

你最好直接使用JSON字符串,而不是在這裏解析它。希望它有幫助

+0

但我有一個List 參數添加到請求。如果我以String格式創建自己的JSON,我必須手動執行它?感謝所有。 –

+1

最後我明白了!非常感謝新! –

+0

嗨,Neo,我已根據您的建議發佈了JSON。我如何查詢ASP.Net服務器中的參數? – Karthick

1
Try this,It may help u 

    public void executeHttpPost(String string) throws Exception 
    { 
     //This method for HttpConnection 
      try 
      { 
      HttpClient client = new DefaultHttpClient(); 

      HttpPost request = new HttpPost("URL"); 

      List<NameValuePair> value=new ArrayList<NameValuePair>(); 

      value.add(new BasicNameValuePair("Name",string)); 

      UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value); 

      request.setEntity(entity); 

      client.execute(request); 

      System.out.println("after sending :"+request.toString()); 

      } 
     catch(Exception e) {System.out.println("Exp="+e); 
      } 

} 
+0

這正是我所做的,因爲在我的代碼中,參數是一個List 。顯然,這對我來說並不適用:S非常感謝任何地方=) –

+1

可以在日誌中發佈錯誤.. – Sree

+0

E/Error用戶(371):錯誤500::'play.exceptions.JavaExecutionException',01-22 10 :43:06.582:E/Error Users(371):message:com.google.gson.stream.MalformedJsonException:使用jsonReader.setLenient(true)在idUser1 = 57&idUser2 = 65附近接受格式錯誤的JSON E/Error用戶(371) :' E/Error用戶(371):錯誤500:'play.exceptions.JavaExecutionException', E/Error用戶(371):message:'這不是JSON對象。 E/Error用戶(371):錯誤500:'play.exceptions。JavaExecutionException', E/Error用戶(371):消息:'期待找到的對象:'名稱'' –