2011-07-21 67 views
0

我想在java中爲android發送POST請求。http對android的發佈請求

我用這個代碼:

HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("myUrl"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("artist", "Amy Macdonald")); 
     nameValuePairs.add(new BasicNameValuePair("title", "Don't Tell Me That It's Over")); 
     nameValuePairs.add(new BasicNameValuePair("album", "Don't Tell Me That It's Over")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

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

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 

的問題是,當我使用:

HttpResponse response = httpclient.execute(httppost); 

我得到一個異常,而這個web服務的工作是肯定的,

回答

0

你發佈什麼方案? http還是https?您是否已使用ClientConnectionManagerHttpParams正確設置客戶端?你在日誌中遇到什麼異常?

我一些代碼,我有張貼數據之間看到的唯一區別(假設你的客戶是否設置正確)是,我使用的HttpContext的執行方法是這樣的:

httpPost = new HttpPost(urlString); 
httpPost.setEntity(new UrlEncodedFormEntity(nvps)); 
response = httpClient.execute(httpPost, httpContext); 
statusCode = response.getStatusLine().getStatusCode(); 

文意是建立在與

httpContext = new BasicHttpContext(); 
httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore()); 

如果您使用的是HTTPS的構造函數,你需要安裝客戶端,與更多的信息,以便它可以處理密鑰存儲要求和連接等安全方面。

0

Javadoc狀態:

用作HTTP消息元素的名稱/值對參數。

parameter    = attribute "=" value 
attribute    = token 
value     = token | quoted-string 

由於HTTP POST不追加屬性的URL(每說),它做它實體主體形式。你可以有一個簡單的基於字符串的實體或基於MIME的實體主體。

NameValuePair已經實現了一個名爲BasicNameValuePair的類(您可以想象它使用HTTP參數)提供了一個參數和一個值。