在Android中发送HTTP帖子

时间:2015-08-07 09:35:51

标签: android

我很难找到一种在Android中发送HTTP POST的方法。我只是想将一些参数发送到服务器。

StackOverflow上有很多问题,所有问题都有非常相似的答案,但许多解决方案现已弃用。

我在这里看到的一个流行的解决方案是:

public void postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");

    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "123"));
        nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

    } catch (ClientProtocolException e) {
        // Catch Protocol Exception
    } catch (IOException e) {
        // Catch IOException
    }
} 

但是,此处的许多组件现已弃用,例如HttpClient,HttpPost和HttpResponse - 因此无法再使用它。

是否有一种新的,同样简单的方法可以做到这一点?我的大多数研究都指向了Volley,但对于这样一个简单的任务来说似乎不必要的复杂。

4 个答案:

答案 0 :(得分:0)

最好使用HttpUrlConnection

connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");

答案 1 :(得分:0)

您可以使用OkHttpgithub link),它是Android开发中非常实用且方便的HTTP工具。

答案 2 :(得分:0)

以下是我发出HTTP POST请求的方式:

private JSONObject doPostRequest(String url,
                                     Map<String, String> params) throws
            IOException, JSONException {

    HttpURLConnection con;
    StringBuilder postParam = new StringBuilder();
    for (String key : params.keySet()) {
        postParam.append(key).append("=").append(params.get(key)).append("&");
    }
    String urlParameters = postParam.toString();
    byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
    int postDataLength = postData.length;

    URL toUrl = new URL(url);

    con = (HttpURLConnection) toUrl.openConnection();
    con.setConnectTimeout(TIME_OUT);
    con.setReadTimeout(TIME_OUT);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("charset", "utf-8");
    con.setRequestProperty("Content-Length", Integer.toString(postDataLength));

    OutputStream wr = con.getOutputStream();
    wr.write(postData);
    wr.flush();
    wr.close();

    con.connect();

    InputStream in;
    try {
        in = con.getInputStream();
    } catch (IOException e) {
        in = con.getErrorStream();
    }
    byte[] buffer = new byte[128];
    int lent;
    StringBuilder response = new StringBuilder();
    while ((lent = in.read(buffer)) != -1) {
        response.append(new String(buffer, 0, lent));
    }
    in.close();
    con.disconnect();

    return new JSONObject(response.toString());
}

我的项目工作得很好。希望对你有所帮助。

答案 3 :(得分:0)

Volley Library使这项工作变得非常简单,并且可以处理所有其他相关任务。
请点击链接,了解如何实现它:https://developer.android.com/training/volley/request.html