2015-05-14 46 views
1

我試圖用以下方法從Android應用程序的服務器發送數據:問題與httpPost.setEntity的Android

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { 

     try{ 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      for (int i=0; i<params.size(); i++) { 
       Log.v("askj",params.get(i).toString()); 
      } 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      try { 
       Log.v("askj","HTTP Entity : " + convertStreamToString(httpPost.getEntity().getContent())); 
      }catch (Exception e){ 
       e.printStackTrace(); 
      } 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
      Log.v("askj",json); 
      Log.e("JSON", json); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 

我肯定知道,我要有正確的參數,網址很好,但代碼httpPost.setEntity(new UrlEncodedFormEntity(params));不起作用。正在訪問的網址沒有這些參數。 httpClient.execute(httpPost);只是訪問沒有任何參數的初始url。我該如何解決這個問題?我試圖使用URI而不是setEntity,但我不知道如何一次追加可變數量的參數。

編輯:我測試了我的服務與郵遞員和網站可以處理POST請求,所以問題是與JSONParser。

+0

注折舊在默認的Android HTTP棧,看看使用Apache的HttpClient,而不是... http://hc.apache.org/httpcomponents-client-ga/ httpclient/apidocs/org/apache/http/client/entity/UrlEncodedFormEntity.html –

+0

你能舉個例子嗎? –

+0

https://hc.apache.org/httpcomponents-client-4.4.x/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java –

回答

0

嘗試指定這樣的編碼格式:

httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8")); 
+0

我得到一個錯誤'在HTTPEnclosingRequestBase不能應用於URLEncodedFormEntity,java.lang.String' –

+0

您只能設置一個實體作爲參數我認爲 –

+0

@BogdanDaniel對不起,該編碼是UrlEncodedFormEntity方法..請參閱我更新的答案和再試一次! –