从DefaultHttpClient更改为HttpURLConnection

时间:2016-05-23 12:09:19

标签: android

我是Android开发的新手,到现在为止我正在使用DefaultHttpClient进行服务调用我需要使用HttpURlConnection,因为DefaultHttpClient已被删除。我怎么能实现这个???

我的DefaultHttpClient代码是

 public String makeServiceCall(String url, int method,
                                  List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;


            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
            Constant.statusCode = httpResponse.getStatusLine().getStatusCode();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    }

我在AsyncTask的doInBackground中调用此方法为

 ServiceHandler serviceHandler = new ServiceHandler();
                String jsonResponse = serviceHandler.makeServiceCall(url, serviceHandler.POST, pairs);

1 个答案:

答案 0 :(得分:1)

要构建您的URL使用此,这是一个示例:

Uri.Builder builder = new Uri.Builder();
builder.scheme(BUILDER_SCHEME) // http
    .authority(BUILDER_AUTHORITY) //api.themoviedb.org
    .appendPath(BUILDER_PATH_1) // 3
    .appendPath(BUILDER_PATH_2) // movie
    .appendPath(params[0]) // now_playing
    .appendQueryParameter(APIKEY_PARAM, "key"); //my api key 
String builtURL = builder.build().toString();

结果是:http://api.themoviedb.org/3/movie/now_playing?api_key=key

声明你的对象:

HttpURLConnection httpURLConnection = null;

初​​始化:

URL url = new URL(builtURL);
httpURLConnection = (HttpURLConnection) url.openConnection();

设置连接的请求方法:

httpURLConnection.setRequestMethod("GET");

连接:

httpURLConnection.connect();

如果你想要一个状态码&amp;回应:

httpURLConnection.getResponseCode();
httpURLConnection.getInputStream();

这是一个非常简单的例子,但是,如果你可以的话,试试Retrofit。