本文转自:http://blog.csdn.net/xiazdong/article/details/7724349

一、HttpClient介绍

 
HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器;
 
Android已经集成了HttpClient,因此可以直接使用;
 
注:此处HttpClient代码不只可以适用于Android,也可适用于一般的Java程序;
 
HTTP GET核心代码:
 
(1)DefaultHttpClient client = new DefaultHttpClient();
(2)HttpGet get = new HttpGet(String url);//此处的URL为http://..../path?arg1=value&....argn=value
(3)HttpResponse response = client.execute(get); //模拟请求
(4)int code = response.getStatusLine().getStatusCode();//返回响应码
(5)InputStream in = response.getEntity().getContent();//服务器返回的数据
 
 
HTTP POST核心代码:
 
(1)DefaultHttpClient client = new DefaultHttpClient();
(2)BasicNameValuePair pair = new BasicNameValuePair(String name,String value);//创建一个请求头的字段,比如content-type,text/plain
(3)UrlEncodedFormEntity entity = new UrlEncodedFormEntity(List<NameValuePair> list,String encoding);//对自定义请求头进行URL编码
(4)HttpPost post = new HttpPost(String url);//此处的URL为http://..../path
(5)post.setEntity(entity);
(6)HttpResponse response = client.execute(post);
(7)int code = response.getStatusLine().getStatusCode();
(8)InputStream in = response.getEntity().getContent();//服务器返回的数据
 

二、服务器端代码

 
服务器端代码和通过URLConnection发出请求的代码不变:
 
  1. package org.xiazdong.servlet;
  2. import java.io.IOException;
  3. import java.io.OutputStream;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.annotation.WebServlet;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. @WebServlet("/Servlet1")
  10. public class Servlet1 extends HttpServlet {
  11. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. String nameParameter = request.getParameter("name");
  13. String ageParameter = request.getParameter("age");
  14. String name = new String(nameParameter.getBytes("ISO-8859-1"),"UTF-8");
  15. String age = new String(ageParameter.getBytes("ISO-8859-1"),"UTF-8");
  16. System.out.println("GET");
  17. System.out.println("name="+name);
  18. System.out.println("age="+age);
  19. response.setCharacterEncoding("UTF-8");
  20. OutputStream out = response.getOutputStream();//返回数据
  21. out.write("GET请求成功!".getBytes("UTF-8"));
  22. out.close();
  23. }
  24. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  25. request.setCharacterEncoding("UTF-8");
  26. String name = request.getParameter("name");
  27. String age  = request.getParameter("age");
  28. System.out.println("POST");
  29. System.out.println("name="+name);
  30. System.out.println("age="+age);
  31. response.setCharacterEncoding("UTF-8");
  32. OutputStream out = response.getOutputStream();
  33. out.write("POST请求成功!".getBytes("UTF-8"));
  34. out.close();
  35. }
  36. }
 

三、Android客户端代码

 
效果如下:
 
 
 

在AndroidManifest.xml加入:

  1. <uses-permission android:name="android.permission.INTERNET"/>
 
MainActivity.java
 
  1. package org.xiazdong.network.httpclient;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.URLEncoder;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.NameValuePair;
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;
  11. import org.apache.http.client.methods.HttpGet;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.impl.client.DefaultHttpClient;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import android.app.Activity;
  16. import android.os.Bundle;
  17. import android.view.View;
  18. import android.view.View.OnClickListener;
  19. import android.widget.Button;
  20. import android.widget.EditText;
  21. import android.widget.Toast;
  22. public class MainActivity extends Activity {
  23. private EditText name, age;
  24. private Button getbutton, postbutton;
  25. private OnClickListener listener = new OnClickListener() {
  26. @Override
  27. public void onClick(View v) {
  28. try{
  29. if(postbutton==v){
  30. /*
  31. * NameValuePair代表一个HEADER,List<NameValuePair>存储全部的头字段
  32. * UrlEncodedFormEntity类似于URLEncoder语句进行URL编码
  33. * HttpPost类似于HTTP的POST请求
  34. * client.execute()类似于发出请求,并返回Response
  35. */
  36. DefaultHttpClient client = new DefaultHttpClient();   //这里的DefaultHttpClient现在已经过时了,现在用的是HttpClient
  37. List<NameValuePair> list = new ArrayList<NameValuePair>();
  38. NameValuePair pair1 = new BasicNameValuePair("name", name.getText().toString());
  39. NameValuePair pair2 = new BasicNameValuePair("age", age.getText().toString());
  40. list.add(pair1);
  41. list.add(pair2);
  42. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
  43. HttpPost post = new HttpPost("http://192.168.0.103:8080/Server/Servlet1");
  44. post.setEntity(entity);
  45. HttpResponse response = client.execute(post);
  46. if(response.getStatusLine().getStatusCode()==200){
  47. InputStream in = response.getEntity().getContent();//接收服务器的数据,并在Toast上显示
  48. String str = readString(in);
  49. Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
  50. }
  51. else Toast.makeText(MainActivity.this, "POST提交失败", Toast.LENGTH_SHORT).show();
  52. }
  53. if(getbutton==v){
  54. DefaultHttpClient client = new DefaultHttpClient();
  55. StringBuilder buf = new StringBuilder("http://192.168.0.103:8080/Server/Servlet1");
  56. buf.append("?");
  57. buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&");
  58. buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8"));
  59. HttpGet get = new HttpGet(buf.toString());
  60. HttpResponse response = client.execute(get);
  61. if(response.getStatusLine().getStatusCode()==200){
  62. InputStream in = response.getEntity().getContent();
  63. String str = readString(in);
  64. Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
  65. }
  66. else Toast.makeText(MainActivity.this, "GET提交失败", Toast.LENGTH_SHORT).show();
  67. }
  68. }
  69. catch(Exception e){}
  70. }
  71. };
  72. @Override
  73. public void onCreate(Bundle savedInstanceState) {
  74. super.onCreate(savedInstanceState);
  75. setContentView(R.layout.main);
  76. name = (EditText) this.findViewById(R.id.name);
  77. age = (EditText) this.findViewById(R.id.age);
  78. getbutton = (Button) this.findViewById(R.id.getbutton);
  79. postbutton = (Button) this.findViewById(R.id.postbutton);
  80. getbutton.setOnClickListener(listener);
  81. postbutton.setOnClickListener(listener);
  82. }
  83. protected String readString(InputStream in) throws Exception {
  84. byte[]data = new byte[1024];
  85. int length = 0;
  86. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  87. while((length=in.read(data))!=-1){
  88. bout.write(data,0,length);
  89. }
  90. return new String(bout.toByteArray(),"UTF-8");
  91. }
  92. }

用HttpClient模拟HTTP的GET和POST请求(转)的更多相关文章

  1. Android入门:用HttpClient模拟HTTP的GET和POST请求

    一.HttpClient介绍   HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器:   Android已经集成了HttpClient,因此可以直接使用: ...

  2. HttpClient模拟http请求

    Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...

  3. 一步步教你为网站开发Android客户端---HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新ListView

    本文面向Android初级开发者,有一定的Java和Android知识即可. 文章覆盖知识点:HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新List ...

  4. httpClient模拟浏览器发请求

    一.介绍 httpClient是Apache公司的一个子项目, 用来提高高效的.最新的.功能丰富的支持http协议的客户端编程工具包.完成可以模拟浏览器发起请求行为. 二.简单使用例子 : 模拟浏览器 ...

  5. 关于HttpClient模拟浏览器请求的參数乱码问题解决方式

    转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/44407297 http://www.llwjy.com/blogdetail/9 ...

  6. HTTPClient模拟Get和Post请求

    一.模拟Get请求(无参) 首先导入HttpClient依赖 <dependency> <groupId>org.apache.httpcomponents</group ...

  7. JAVA--利用HttpClient模拟浏览器登陆请求获取响应的Cookie

    在通过java采集网页数据时,我们常常会遇到这样的问题: 站点需要登陆才能访问 而这种网站,一般都会对请求进行账号密码的验证,验证的方式也有多种,需要具体分析. 今天分析其中的一种情况: 站点对登陆密 ...

  8. 记一次HTTPClient模拟登录获取Cookie的开发历程

    记一次HTTPClient模拟登录获取Cookie的开发历程 环境: ​ springboot : 2.7 ​ jdk: 1.8 ​ httpClient : 4.5.13 设计方案 ​ 通过新建一个 ...

  9. [Java] 模拟HTTP的Get和Post请求

    在之前,写了篇Java模拟HTTP的Get和Post请求的文章,这篇文章起源与和一个朋友砍飞信诈骗网站的问题,于是动用了Apache的comments-net包,也实现了get和post的http请求 ...

随机推荐

  1. C++ 找不到方法标识符

    其实原因是这个CPP并没有面向对象的结构. 所以进行编译时是“顺序编译”的,而main函数的定义又在A的定义之前.自然找不到标识符了.

  2. AC日记——宠物收养所 bzoj 1208

    1208 思路: 一棵splay树: 如果来者是宠物且树空,就将其加入树中: 如果树不空,则查找前驱后继,取最优,然后删点: 对人亦然: 注意边界和取模,最后的ans用long long其余用int即 ...

  3. JWT在PHP使用及问题处理

    官网 https://jwt.io/ 3.0版本 https://github.com/lcobucci/jwt 安装 composer require lcobucci/jwt 依赖 PHP 5.5 ...

  4. 洛谷——P1119 灾后重建

    P1119 灾后重建 题目背景 B地区在地震过后,所有村庄都造成了一定的损毁,而这场地震却没对公路造成什么影响.但是在村庄重建好之前,所有与未重建完成的村庄的公路均无法通车.换句话说,只有连接着两个重 ...

  5. z-index 基础详解

    关于z-index网上其实有不少博文,写得也不错,不过有些帖子比较旧,而IE也已经更新到了IE11了,所以还是重新总结一下.由于 z-index 的属性表现和层级有关,有些特点在某些层级下才表现出来, ...

  6. IntelliJ IDEA设置鼠标移动到方法上提示API注释

    参考: https://www.cnblogs.com/guazi/p/6474426.html(图片转自此篇文章)

  7. ArcObject开发,程序编译通过,但无法启动的解决

    在ArcGIS 二次开发时,我们很容易就会忽略了,授权方面的问题,尤其是初学者.这方面的问题的解决,主要有: (1)在ArcGIS object控件出现的Form窗体,上添加License Contr ...

  8. 受检查异常要求try catch或者throws,但是要记住只要catch异常了,就不会向下继续抛了

    所以在框架中,要想异常被统一的异常拦截器处理,就要将受检查异常转换为运行异常,在受检查异常的catch时候,手动throw new runtime exception

  9. iphone开发-SQLite数据库使用

    我现在要使用SQLite3.0创建一个数据库,然后在数据库中创建一个表格. 首先要引入SQLite3.0的lib库.然后包含头文件#import <sqlite3.h> [1]打开数据库, ...

  10. iis无法启动的解决办法-卸掉KB939373补丁

    在本地计算机无法启动 world wide web Publishing 服务错误127:找不到指定的程序 在网上搜索了一下,发现,回答的五花八门, 1.有的说重新安装IIS的,(我重新安装了,还是不 ...