2013-10-27 68 views
0

我使用下面的代碼,使但是,在我的理解我現在用的是POST方法爲.Net Web API的連接,因爲我使用HttpPost對象,但阿比說:如何使一個POST請求API

The requested resource does not support http method 'GET'. 

我的代碼:

private boolean POST(List<NameValuePair>[] nvPair) { 

    HttpClient httpclient = new DefaultHttpClient(); 
    String UrlString = URLEncodedUtils.format(nvPair[0], "utf-8"); 
    HttpPost httppost = new HttpPost(apiBaseUri + UrlString); 

    try { 
     httppost.setEntity(new UrlEncodedFormEntity(nvPair[0])); 
     HttpResponse response = httpclient.execute(httppost); 
     String respond = response.getStatusLine().getReasonPhrase(); 
     Log.d("MSG 3 > ", respond); 

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

回答

2

要發送HTTP POST請求

String UrlString = URLEncodedUtils.format(nvPair[0], "utf-8"); 
      URL url = new URL(apiBaseUri + UrlString); 
      HttpURLConnection connection = (HttpURLConnection) url 
        .openConnection(); 
      connection.setRequestProperty("User-Agent", "android"); 
      connection.setRequestProperty("Accept", "application/json"); 

      connection.setRequestMethod("POST"); 
      connection.setDoInput(true); 
      int responseCode = connection.getResponseCode(); 
      String response = readResponse(connection);