从HttpClient到HttpURLconnection

时间:2016-02-01 08:28:54

标签: android httpclient httpurlconnection

我想升级我的代码以发布json。 第一个实现HttpClient,它工作正常! 我尝试使用HttpURLconnection的新实现,它不起作用!我无法发送任何帖子请求。 我缺少什么?

public class AsyncPostBG extends AsyncTask<String, String, String> {

    private ProxyState mData = null;
    private String mName = null;

    public AsyncPostBG(ProxyState data, String name)
    {
        mData = data;
        mName = name;
    }

    @Override
    protected String doInBackground(String... params){
        HttpParams httpParams = new BasicHttpParams();
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        HttpPost postMethod = new HttpPost(params[0]);
        postMethod.setHeader("Content-Type", "application/json; charset=utf-8");
        postMethod.setHeader("Accept", "*/*");
        postMethod.setHeader("Accept-Encoding", "gzip, deflate");
        Gson gson=new Gson();
        String json = gson.toJson(mData);
        try {
            postMethod.setEntity(new ByteArrayEntity(json.getBytes("UTF8")));
            HttpResponse response = httpClient.execute(postMethod);
            StatusLine statusLine = response.getStatusLine();
        }
        catch (UnsupportedEncodingException e){

        }
        catch (Exception e) {
        }
        return json;
    }
}

这是我的HttpURLConnection实现:

private class AsyncStatePostBG extends AsyncTask<String, Void,  String> {
    private ProxyObj mData = null;
    private String mName = null;

    public AsyncStatePostBG(ProxyObj data, String name) {
        mData = data;
        mName = name;
    }

    @Override
    protected String doInBackground(String... params) {
        Gson gson = new Gson();
        String json = gson.toJson(mData);

        HttpURLConnection connection = null;
        try {
            URL object = new URL(ComURL + "api/state/" + mName);
            connection = (HttpURLConnection) object.openConnection();

            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.connect();
            OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
            streamWriter.write(json);
            streamWriter.flush();
            streamWriter.close();

        } catch (Exception exception) {

            return null;
        }
        return json;

    }
}

1 个答案:

答案 0 :(得分:3)

你可以直接使用这段代码,它对我有用..

     URL url = new URL("Your URL");
     HttpURLConnection httpsURLConnection = (HttpURLConnection)url.openConnection();
     httpsURLConnection.setReadTimeout(15000);
     httpsURLConnection.setConnectTimeout(20000);
     httpsURLConnection.setDoInput(true);
     httpsURLConnection.setRequestProperty("Content-Type", "application/json");
//Method Type
     httpsURLConnection.setRequestMethod("POST" : "PUT");
     OutputStream outputStream = httpsURLConnection.getOutputStream();
     BufferedWriter bufferedWriter = new BufferedWriter(new   OutputStreamWriter(outputStream, "UTF-8"));
     bufferedWriter.write("Your Params");
     bufferedWriter.flush();
     bufferedWriter.close();
     outputStream.close();
     httpsURLConnection.connect();    
     int mStatus = httpsURLConnection.getResponseCode();

检查响应代码,并获得如下结果

if (mStatus == 200 || mStatus == 201)
 return readResponse(httpsURLConnection.getInputStream()).toString();

获得回复的方法..

private static StringBuilder readResponse(InputStream inputStream) throws IOException, NullPointerException {
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder;
    }