如何向api发出POST请求

时间:2013-10-27 19:52:20

标签: java android

我正在使用以下代码建立与.Net Web API的连接,但据我了解,我使用的是POST方法,因为我使用的是HttpPost对象,但api说:< / p>

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;
}

1 个答案:

答案 0 :(得分: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);
相关问题