• HttpClient之带参数的post请求


     具体代码:

    package cn.itcast.crawler.test;

    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;

    public class HttpPostParamTest {
    public static void main(String[] args) throws Exception {
    //1.创建HttpClient对象
    CloseableHttpClient httpClient= HttpClients.createDefault();
    //2.创建HttpPost对象,设置URL地址
    HttpPost httpPost=new HttpPost("http://yun.itheima.com/search");;

    //声明list集合,用来分装表单中的参数
    //要求:设置请求的地址是:http://yun.itheima.com/search?keys=java
    List<NameValuePair> params=new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("keys","java"));
    // 创建表单的Entity对象,第一个参数是封装好的表单数据,第二个参数就是编码方式
    UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(params,"utf8");
    //设置表单的Entity对象到Post请求中
    httpPost.setEntity(formEntity);


    //使用httpClient发起响应获取repsonse
    CloseableHttpResponse response=null;
    try {
    response=httpClient.execute(httpPost);
    //4.解析响应,获取数据
    //判断状态码是否是200
    if(response.getStatusLine().getStatusCode()==200){
    HttpEntity httpEntity=response.getEntity();
    String content=EntityUtils.toString(httpEntity,"utf8");
    System.out.println(content.length());
    }
    } catch (IOException e) {
    e.printStackTrace();
    }finally {
    try {
    response.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    try {
    httpClient.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    }
    }
    执行结果:

     在带参数的post请求中,参数并不会出现在地址栏中,

    与不带参数的post请求相比较,带参数的post代码的核心内容就是上面代码中添加了背景颜色的代码

  • 相关阅读:
    [netty] netty中的定时机制HashedWheelTimer 规格严格
    c和c++开发工具之clion和vs
    编译python(cpython)的源码及其用途
    python缩进tab和空格互转
    c和c++编译器之gcc和mingw
    DotLiquid(.net模版引擎)
    微信公众号自定义菜单的一些思考我为什么做公众号自定义菜单
    Owner项目步骤
    xx系统分析说明书
    项目经理养成计划
  • 原文地址:https://www.cnblogs.com/juddy/p/13116089.html
Copyright © 2020-2023  润新知