2012-05-30 25 views
0

我需要在我的應用中做簡單的http post。在Android應用中使用http post

找到示例並創建了AsyncTask類。做後的主要代碼是這樣的:

nameValuePairs - 是柱元件

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(URL_STRING); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); 
HttpResponse response = httpclient.execute(httppost); 
String data = new BasicResponseHandler().handleResponse(response); 

我如何過這種例外

org.apache.http.client.HttpResponseException: Forbidden 

這是什麼意思?如果這個服務返回的東西,那麼如何看到完整的消息?

此外,如果有其他的方法,使HTTP POST,我可以試試:)

謝謝你們的幫助。

+1

你添加INTERNET權限到menifest文件? –

回答

0

例外org.apache.http.client.HttpResponseException如此處所述發出非2xx HTTP響應:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/HttpResponseException.html

您可以使用如下的簡單方法httpPOST:

  HttpClient httpclient = new DefaultHttpClient();  
     HttpPost httppost = new HttpPost("http://Your URL/");  
     try {   
     // Add your data   
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);   
     nameValuePairs.add(new BasicNameValuePair("Name1", "Value1"));   
     nameValuePairs.add(new BasicNameValuePair("Name2", "Value2"));  
     nameValuePairs.add(new BasicNameValuePair("Name3", "Value3"));  

      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 
      }