HttpURLConnection,HttpClient,Volley(2)

AndroidManifest.xml 别忘了添加权限

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.hurlconnectionpic" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET"/> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.hurlconnectionpic.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

效果图:

这里写图片描述

HttpClient

HttpURLConnection是Java的网络库的类,而HttpClient是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient相对HttpURLConnection功能更加完善易用,主要特点如下:
(1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
(2)支持自动转向
(3)支持 HTTPS 协议
(4)支持代理服务器等

使用步骤:

GET:
1. 创建 HttpClient 的实例
2. 创建某HttpGet。在创建时传入待连接的地址
3. 调用HttpClient实例的 execute 方法来执行第二步中创建好的实例
4. 读 response
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理
POST:
1. 创建 HttpClient 的实例
2. 创建HttpPost对象。调用setParams(HetpParams params),setEntity(HttpEntity entity)方法来设置请求参数
3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
4. 读 response,getAllHeaders(),getEntity()等
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理

示例代码: //Get 方式 CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://targethost/homepage"); CloseableHttpResponse response1 = httpclient.execute(httpGet); // 下面的HTTP连接一直被response持有,从而使response内容可以直接从网络socket中传输。 //为了保证系统资源能够正确释放,用户必须在finally区块中调用CloseableHttpResponse.close()方法 //需要注意:如果response内容没有完全接受,下面的连接是不能安全的复用的,连接将会关闭并被connection manager丢弃。 try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); //确保response内容全被接受,使用 EntityUtils.consume(entity1); } finally { response1.close(); } //Post 方式 HttpPost httpPost = new HttpPost("http://targethost/login"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new BasicNameValuePair("password", "secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); }

1

上面代码展示了使用GET和POST两种方式来完成HTTP会话过程。更多信息可以参考apache的网站上的资源:
HttpClient Tutorial ()
HttpClient API文档:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/bbb2a0b66b66e00712b3a71d4a856c84.html