掌握HttpClient类的GET和POST请求访问服务器步骤!
2015-09-07 09:19
711 查看
HttpClient 是HttpConnection的增强 (网络访问)
HttpClient需要导入第三方库的jar包:
在当前工程下新建以文件夹,用来存放第三个的jar文件,比如叫做:libs
全选jar包,右击选择buildpath
[b](1)使用HttpClient采用GET提交访问访问服务器端并得到服务器端返回的数据
[/b]
//1.实例化HttpClient对象,相当于用户实例化了浏览器对象
HttpClient httpClient=new DefaultHttpClient();
//2.实例化HttpGet对象并指定访问网址,相当于用户实例化了GET请求对象
HttpGet httpGet=new HttpGet(path);
try {
/*
* 3.调用httpClient对象的execute()方法传递请求对象得到响应对象
*
* 本次操作干了两件事:
* 1.将get请求提交到服务器
* 2.得到服务器发送过来的数据
*/
HttpResponsehttpResponse= httpClient.execute(httpGet);
//4.得到服务器的响应码(状态码)
intresponseCode=httpResponse.getStatusLine().getStatusCode();
//如果本次访问服务器端成功
if(responseCode==HttpStatus.SC_OK)
//使用HttpClient访问服务器端也能得到输入流对象
//InputStreaminputStream=httpResponse.getEntity().getContent();
//5.得到服务器端发送过来的数据并封装成HttpEntity对象
HttpEntityhttpEntity=httpResponse.getEntity();
//6.将对象转化成字符串
Stringresult=EntityUtils.toString(httpEntity);
(2)使用HttpClient采用POST提交访问访问服务器端并得到服务器端返回的数据
* @param path
*/
private static voidsendRequestByPost(String path) {
//1.实例化HttpClient对象,相当于用户实例化了浏览器对象
HttpClient httpClient=new DefaultHttpClient();
//2.实例化HttpPost对象并指定访问网址,相当于用户实例化了Post请求对象
HttpPost httpPost=new HttpPost(path);
try {
//3.设置Post请求需要传递的参数
List<NameValuePair>parameters=new ArrayList<NameValuePair>();
parameters.add(newBasicNameValuePair("userName", "张三"));
parameters.add(newBasicNameValuePair("pwd", "123"));
HttpEntityhttpEntityParameter=new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(httpEntityParameter);
/*
* 4.调用httpClient对象的execute()方法传递请求对象得到响应对象
*
* 本次操作干了两件事:
* 1.将postt请求提交到服务器
* 2.得到服务器发送过来的数据
*/
HttpResponsehttpResponse= httpClient.execute(httpPost);
//5.得到服务器的响应码(状态码)
intresponseCode=httpResponse.getStatusLine().getStatusCode();
//如果本次访问服务器端成功
if(responseCode==HttpStatus.SC_OK){
//使用HttpClient访问服务器端也能得到输入流对象
//InputStreaminputStream=httpResponse.getEntity().getContent();
//6.得到服务器端发送过来的数据并封装成HttpEntity对象
HttpEntityhttpEntity=httpResponse.getEntity();
//7.将对象转化成字符串
Stringresult=EntityUtils.toString(httpEntity);
相关文章推荐
- Android笔记(二十二) HttpURLConnection
- Linux 网络配置
- 根文件系统的挂载过程 http://blog.sina.com.cn/s/blog_67e2ef6a0100s8kf.html
- http tcp ip 模型解释 ngix expoll select apache
- 网络数据挖掘程序的设计
- 黑马程序员-Java基础:网络编程
- java之--------socket编程(TCP)服务器请求与客户端
- HttpURLConnection post请求
- hdu 4280 Island Transport 【网络流+优化】
- 网络部分(一)
- 菜鸟学matlab之智能算法(2)——————————BP神经网络算法
- 移动应用网络优化
- 计算机网络面试题
- HttpServletResponse 小知识
- SOAP and .net services for Apache HTTP Server
- iOS开发之加载大量网络图片优化
- 浏览器相关技术介绍
- 使用 libevent 和 libev 提高网络应用性能——I/O模型演进变化史
- Andorid 分别用AsyncTask和Handler下载网络图片
- AS3.0中用于网络通信的类总结