2010-09-08 72 views
1

我一直在研究將GET和POST請求同時用於Web服務的應用程序。 GET請求沒有問題,但POST請求正在殺死我。我已經在代碼中嘗試了兩種不同的場景。第一個看起來像這樣...無法通過我的Android應用程序對Web服務執行HTTP發佈

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(ws); 
JSONObject jsonObject = new JSONObject(); 

try { 
// Add your data 
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
jsonObject.put("action", "login"); 
jsonObject.put("username", "*********"); 
    jsonObject.put("password", "*********"); 

    httppost.setHeader("jsonString", jsonObject.toString()); 
StringEntity se = new StringEntity(jsonObject.toString());  
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
httppost.setEntity(se); 


      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 
      textview.setText(getResponse(response.getEntity())); 
     } catch (ClientProtocolException e) { 
      textview.setText(e.getLocalizedMessage()); 
     } catch (IOException e) { 
      textview.setText(e.getLocalizedMessage()); 
     } catch (JSONException e) { 
      textview.setText(e.getLocalizedMessage()); 
     } 

這段代碼獲得這個結果對我來說...
「錯誤的請求(無效標題名稱)」

現在,這裏是我的第二一段代碼。 ..

HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(ws); 
     JSONObject jsonObject = new JSONObject(); 

     try { 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      jsonObject.put("action", "login"); 
      jsonObject.put("username", "******"); 
      jsonObject.put("password", "******"); 

      nameValuePairs.add(new BasicNameValuePair("jsonString", jsonObject.toString())); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 

      textview.setText(getResponse(response.getEntity())); 
     } catch (ClientProtocolException e) { 
      textview.setText(e.getLocalizedMessage()); 
     } catch (IOException e) { 
      textview.setText(e.getLocalizedMessage()); 
     } catch (JSONException e) { 

     } 

這給了我一個完全不同的結果。這是一個很長的亂碼XML和SOAP,它有一個SOAP異常中提到它...
「服務器無法處理請求--- System.Xml.XmlException:數據在根級別無效。 1,位置1「。
現在,任何人都可以闡明我做錯了什麼。

回答

2

在你的第二個代碼段添加::

// Execute HTTP Post Request 
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, HTTP.UTF_8); 
    httppost.setEntity(formEntity); 
    HttpResponse response = httpclient.execute(httppost); 
+0

添加該位讓我得到了相同的XML SOAP錯誤。 – huffmaster 2010-09-08 12:07:32

0

這是有點老了,但有一個類似的問題我自己。第一個例子是我去的路線;原始示例的問題是此行httppost.setHeader("jsonString", jsonObject.toString());。它添加了服務器無法解析的請求標頭。

此外,nameValuePairs的聲明是不必要的。

相關問題