如何将httpclient更改为HttpURLConnection

时间:2018-05-24 14:32:56

标签: android httprequest httpurlconnection

**我有这个代码,我想将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;
     }
}

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

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