как изменить httpclient на HttpURLConnection - PullRequest
0 голосов
/ 24 мая 2018

** У меня есть этот код, и я хочу изменить 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 голосов
/ 24 мая 2018

Вы можете использовать что-то вроде:

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