掌握HttpClient类的GET和POST请求访问服务器步骤!
来源:互联网 发布:淘宝学习网站 编辑:程序博客网 时间:2024/05/29 18:51
HttpClient 是HttpConnection的增强 (网络访问)
HttpClient需要导入第三方库的jar包:
在当前工程下新建以文件夹,用来存放第三个的jar文件,比如叫做:libs
全选jar包,右击选择buildpath
(1)使用HttpClient采用GET提交访问访问服务器端并得到服务器端返回的数据
//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);
- 掌握HttpClient类的GET和POST请求访问服务器步骤!
- Httpclient的Get请求和Post请求
- HttpClient的Get请求和Post请求
- HttpClient请求服务器 get post
- httpclient的get和post请求
- HttpClient的get和post请求数据
- HttpClient 的post和get请求
- httpClient的Get和Post请求
- HttpClient的post和get请求
- httpclient的get和post请求
- HttpClient的GET和POST请求
- HttpClient get和HttpClient Post请求的方式获取服务器的返回数据
- HttpClient get和HttpClient Post请求的方式获取服务器的返回数据
- HttpClient的Post和Get访问网页
- httpClient----Post 和 GET请求
- Httpclient post和get请求
- java使用httpclient封装post请求和get的请求
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- VB短信接口开发经验及具体开发实现
- C++标准库vector及迭代器
- Spring的方法注入
- 《有朝一日》
- MySQL 错误日志 测试
- 掌握HttpClient类的GET和POST请求访问服务器步骤!
- java内部类
- 14个Xcode中常用的快捷键操作
- 自动化测试 之亡羊补牢编
- 欢迎使用CSDN-markdown编辑器
- 通过JDBC操作数据库的标准示例
- Web安全之文件操作
- leetcode系列(25)ZigZag Conversion 锯形转化
- android数据库——GreenDao