HttpClient也是一种Http的网络通信方式,这里同样分为get和post两种方式,我们一起来看一下吧。
一:HttpClient方式----get
在这之前我们同样用上一篇博文中的服务器文件,用来根据传入的参数,返回给客户端信息。具体文件内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <% String a = request.getParameter("a"); String b = request.getParameter("b"); if(a!=null&&b!=null){ out.println(a + b); }else { out.print("error"); } %> | |
具体步骤:
(1)定义一个String类型的字符串,将服务器地址赋值给他,由于这里使用的get方法,所以参数的传递会直接显示在URL路径上。这里同样要注意参数的传递方式。具体如下
1 | String strURL = "http://222.27.166.10:8080/MyServer/youcan.jsp?a=hello&b=word" ; | |
(2)创建数据请求对象HttpGet,并根据标志服务器地址的字符串,实例化请求对象。
1 | httpGet = new HttpGet(strURL); | |
(3)创建客户端对象,用来发送上面的请求。由于它是抽象类,需要通过它的子类去实例化他
1 | httpClient = new DefaultHttpClient(); | |
(4)创建获得响应的对象HttpResponse。用来接收客户端对象执行请求之后,服务器端给你返回的响应对象。
1 | httpResponse = httpClient.execute(httpGet); | |
(5)创建接收信息的对象HttpEntity,通过HttpResponse对象的getEntity()方法获得回应的信息
1 | httpEntity = httpResponse.getEntity(); | |
(6)创建输入流对象,通过HttpEntity对象的getContent方法获得返回信息的内容,通过流对象进行读取输出在TextView控件上。
1 2 3 4 5 6 7 8 9 10 11 | in =httpEntity.getContent(); BufferedReader br = new BufferedReader( new InputStreamReader(in)); String line = null ; StringBuffer sb = new StringBuffer(); while ((line = br.readLine())!= null ) { sb.append(line); } tv.setText(sb.toString()); | |
(7)特别注意的一点:添加网络权限。
1 | <uses-permission android:name= "android.permission.INTERNET" /> | |
结果:在模拟器的频幕上有如下显示,把两个字符串拼接在了一起。

二:HttpClient方式----Post
我们同样引用上一个服务器文件,用来返回拼接好的字符串。
具体操作:
(1)创建数据请求对象HttpPost,这里我们直接通过构造方法中传入标志服务器地址字符串的方式,实例化对象。注意这里的字符串中不能把参数直接写在后面,而是通过以下的方法来携带数据给服务器。
1 | httpPost = new HttpPost( "http://222.27.166.10:8080/MyServer/youcan.jsp" ); | |
(2)创建客户端对象HttpClient
1 | httpClient = new DefaultHttpClient(); | |
(3)创建泛型为BasicNameValuePair的List列表,这个泛型表示的内容就是以键值对的形式,将传递参数的值存储起来。
1 2 3 | List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); list.add( new BasicNameValuePair( "a" , "hello" )); list.add( new BasicNameValuePair( "b" , "word" )); | |
(4)创建数据存储对象UrlEncodedFormEntity,用List存储的数据实例化UrlEncodedFormEntity对象
1 | urlEncodedFormEntity = new UrlEncodedFormEntity(list); | |
(5)给数据请求对象添加传递的参数的值
1 | httpPost.setEntity(urlEncodedFormEntity); | |
(6)实例化接收响应的对象
1 | httpResponse = httpClient.execute(httpPost); | |
(7)创建接收信息的对象HttpEntity,通过HttpResponse对象的getEntity()方法获得回应的信息
1 | httpEntity = httpResponse.getEntity(); | |
(8)创建输入流对象,通过HttpEntity对象的getContent方法获得返回信息的内容,通过流对象进行读取输出在TextView控件上。
1 2 3 4 5 6 7 8 9 | in = httpEntity.getContent(); BufferedReader br = new BufferedReader( new InputStreamReader(in)); String line= null ; StringBuffer sb= new StringBuffer(); while ((line = br.readLine())!= null ) { sb.append(line); } tv.setText(sb.toString()); | |
(9)特别注意:要添加网络通信权限。
1 | <uses-permission android:name= "android.permission.INTERNET" /> | |
结果:在模拟器的频幕上有如下显示,把两个字符串拼接在了一起。(结果同上)
Android中的网络通信,很有用处,比如我们可以通过网络通信方式获得网络中Json字符串,解析出来为我们所用。