2016-05-23 53 views
0

我是Android开发新手,直到现在我正在使用DefaultHttpClient进行服务调用,现在我需要使用HttpURlConnection作为DefaultHttpClient被取消。我怎样才能做到这一点?从DefaultHttpClient更改为HttpURLConnection

我对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

检查此参考:http://www.tutorialspoint.com/android/android_network_connection.htm –

回答

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

如果你想那么一个状态代码&响应:

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

这是一个非常简单的例子,不过,如果你可以,虽然,尝试改造。

+0

我主要关注的是设置参数,并且在你的回答中你没有正确的设置参数......我正在发送List 配对到makeServiceCall方法 –

+0

@raviprakashdarshan,你指的是URL?我会把它放进去。 –

+0

是的。我指的是! –