模拟http发送post请求并返回数据

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。本文首先介绍 HTTPClient,然后根据作者实际工作经验给出了一些常见问题的解决方法。


HttpClient 功能介绍

  • 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
  • 支持自动转向
  • 支持 HTTPS 协议
  • 支持代理服务器等


@Test
 public void asearchTest() {
  String url =“”;
  Executor executor = Executor.newInstance();
  Form form = Form.form();
  form.add("fullnameCn", "张三");
  form.add("identityNumber", "");
  form.add("mobile", "");
  try {
   UrlEncodedFormEntity urlencEntity = new UrlEncodedFormEntity(
     form.build(), "UTF-8");
   Request request = Request.Post(url);
   Response response = executor.execute(request.body(urlencEntity));
   String rtn = response.returnContent().asString();
   System.out.println("rtn=================== begin");
   System.out.println(rtn);
   System.out.println("rtn------------------- end");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }


 @Test
 public void asearch() throws ClientProtocolException, IOException {
  String url = “”;
  CloseableHttpClient chc = HttpClients.createDefault();
  List<NameValuePair> list = new ArrayList<NameValuePair>();
  NameValuePair pair1 = new BasicNameValuePair("fullnameCn", "张三");
  NameValuePair pair2 = new BasicNameValuePair("identityNumber", "");
  NameValuePair pair3 = new BasicNameValuePair("mobile", "");
  list.add(pair1);
  list.add(pair2);
  list.add(pair3);
  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
  HttpPost post = new HttpPost(url);
  post.setEntity(entity);
  HttpResponse response = chc.execute(post);
  String strResult = EntityUtils.toString(response.getEntity());
  System.out.println("rtn=================== begin");
  System.out.println(strResult);
  System.out.println("rtn------------------- end");
 }


 @Test
 public void testPost() {
  String url = “”;

  CloseableHttpClient httpclient = HttpClients.createDefault();
  HttpPost httpPost = new HttpPost(url);
  Form form = Form.form();
  form.add("fullnameCn", "张三");
  form.add("identityNumber", "");
  form.add("mobile", "");
  try {
   httpPost.setEntity(new UrlEncodedFormEntity(form.build(), "UTF-8"));
   CloseableHttpResponse response2 = httpclient.execute(httpPost);
   System.out.println(response2.getStatusLine());
   HttpEntity entity2 = response2.getEntity();
   String rtn = EntityUtils.toString(entity2, "UTF-8");
   System.out.println("--------------------rtn begin");
   System.out.println(rtn);
   System.out.println("====================rtn end");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值