HttpURLConnection和HttpClient的使用

做安卓应用开发离不开与网打道,就要用到Http通信。我们常用的http请求方式有POST和GET两种。GET可以获得静态页面,可以把参数放在URL字符串后面,传递给服务器。而POST方法的参数是放在Http请求中传递给服务器。更详细的区别可以参考博文:。

首先看下HttpURLConnection。HttpURLConnection是继承自URLConnection,对象主要通过URL的openConnection方法获得,如

/**取得HttpURLConnection对象*/

HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();

/**设置输入和输出流*/

/**设置请求方式为POST*/

/**POST请求不能使用缓存*/

/**最后要关闭连接*/

urlConn.disConnection();

不过HttpURLConnection默认使用GET方式,如:HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();、**得到读取的流*/InputStreamReader in = new InputStreamReader(urlConn.getInputStream());/**为输出创建BufferedReader*/BufferedReader buffer = new BufferedReader(in);String inputLine = null;/**循环来读取获得的数据*/while (((inputLine = buffer.readLine()) != null)) { resultData += inputLine + "\n"; } /**关闭流及链接*/in.close();urlConn.disconnect();

————HttpClient—————————-

Apache提供的HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),,即提高了开发的效率,也方便提高代码的健壮性GET方法的操作代码示例如下:

/**请求地址*/String httpUrl = "";/**获取HttpGet连接对象*/HttpGet httpRequest = new HttpGet(httpUrl);/**取得HttpClient*? HttpClient httpclient = new DefaultHttpClient();/**取得HttpResponse*/HttpResponse httpResponse = httpclient.execute(httpRequest);/**判断是否请求成功getStatusCode()==200*/ if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**得到返回的String* String strResult = EntityUtils.toString(httpResponse.getEntity()); }else{ //提示请求错误 }}如果我们使用POST传参时,要使用NameValuePair来保存参数,如:/**请求URL*/String httpUrl = ""; /**用POST方法有获得HttpPost对象*/HttpPost httpRequest = new HttpPost(httpUrl);/**必须要用NameValuePair来保存参数*/List<NameValuePair> params = new ArrayList<NameValuePair>(); /**添加参数值*/params.add(new BasicNameValuePair("userId", "555555"));

params.add(new BasicNameValuePair("passWord", "*******")); /**设置字符集*/HttpEntity httpentity = new UrlEncodedFormEntity(params, "UTF-8");/**请求操作*/ httpRequest.setEntity(httpentity); /**取得HttpClient*/ HttpClient httpclient = new DefaultHttpClient();/**取得Response*/HttpResponse httpResponse = httpclient.execute(httpRequest); /**判断是否连接成功getStatusCode()==200*/ if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**返回结果*/ String strResult = EntityUtils.toString(httpResponse.getEntity()); }else{ //提示错误 }}

青春在我的心中是苦涩的又是甘甜的,是精致的又是粗糙的,

HttpURLConnection和HttpClient的使用

相关文章:

你感兴趣的文章:

标签云: