使用MultipartEntityBuilder POST HttpRequest并且没有弃用的类

时间:2015-06-19 08:08:09

标签: java android

我在我的代码上使用这个方法并且工作正常,但是因为API22 HttPost,HttpClient,HttpEntity ......已被弃用。

我知道正确更新此代码的方法是使用HttpURLConnection,但我不知道如何在MultipartEntityBuilder上使用我的参数。

public JSONObject makeHttpRequest(String url, MultipartEntityBuilder datos) {
    HttpClient httpclient = new DefaultHttpClient();    
      try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(datos.build());
        HttpResponse httpResponse = httpclient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return inputStreamToJSON(is);
}
编辑:所以,我更改了我的代码,现在唯一不推荐使用的类是HttpEntity,我一直在搜索,这是更新后的代码:

public JSONObject makeHttpRequest(String url, MultipartEntityBuilder datos) {
    try {
        HttpEntity entity = datos.build();
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Cache-Control", "no-cache");
        conn.setRequestProperty("Content-length", entity.getContentLength() + "");
        conn.setRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
        OutputStream os = conn.getOutputStream();
        entity.writeTo(os);
        os.close();
        InputStream is = conn.getInputStream();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return inputStreamToJSON(is);
}

1 个答案:

答案 0 :(得分:0)