【问题标题】:how to change httpclient to HttpURLConnection如何将 httpclient 更改为 HttpURLConnection
【发布时间】:2018-11-03 20:05:21
【问题描述】:

**我有这段代码,我想将 Httpclient 更改为 HttpURLConnection,我的 setEntity 方法有问题,我没有找到 HttpURLConnection 的等价物 **

public JSONObject postData(JSONObject jOb) throws Throwable {

 // Create a new HttpClient and Post Header

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://www.blabla");

try {
        httppost.setEntity(new StringEntity(jOb.toString()));
        HttpResponse response = httpclient.execute(httppost);
        String responseText = EntityUtils.toString(response.getEntity());
        return new JSONObject(responseText);
     } catch (Throwable e) {
        ControlTable.logErrors(e.toString() + "\t" + jOb.toString(), 32);
        throw e;
     }
}

【问题讨论】:

  • 根据我的经验,Apache HTTP 客户端比 HttpUrlConnection 更好,更实用。尤其是错误处理对于 HttpURLConnection 来说真的很痛苦。

标签: android httprequest httpurlconnection


【解决方案1】:

你可以使用类似的东西:

URL url = new URL("http://www.blabla.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();

还要写这个函数:

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

【讨论】:

  • 您的答案从响应中读取一个字符串,但问题还包括发送一个字符串作为 POST 正文。
  • 我修正了我的答案。谢谢@罗伯特
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
  • 1970-01-01
相关资源
最近更新 更多