HttpPost 携带参数的请求方式

4 篇文章 0 订阅
2 篇文章 0 订阅

一、HTTP请求

Http的几种请求方式对应程序包中的HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions,这些类均实现了HttpUriRequest接口,所以可以作为execute的执行参数使用。

根据HTTP的请格式,我们可以知道有两种方式可以为request提供参数。

第一种方式:request-line

第二种方式:request-body

因为工作中使用HttpPost请求用到了这两种请求方式,所以下面就只列出HttpPost的请求,其他请求方式的等下次用到在补上。

二、HttpPost

1、request-line方式

  URI uri = null;
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("region", String.valueOf(departmentId)));//需要对应传参的name和value
        qparams.add(new BasicNameValuePair("platNum", carNum));//需要对应传参的name和value
        try {
            uri = URIUtils.createURI("http", "192.168.1.xx:23002", -1, "/zyc/get/latestdd",
                    URLEncodedUtils.format(qparams, "UTF-8"), null);
            HttpPost httpPost = new HttpPost(uri);
            System.out.println(httpPost.getURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

打印结果如下:  http://192.168.1.75:23002/zyc/get/latest?region=320211&platNum

2、request-body

 PageHelper pageHelper =new PageHelper(pageIndex,pageSize,null);
 ObjectMapper MAPPER = new ObjectMapper();
 stringPage = MAPPER.writeValueAsString(pageHelper);//对象转String
 List<NameValuePair> list = new LinkedList<>();
        list.add( new BasicNameValuePair("pageHelper",stringPage ));//pageHelper放在body中传过去
  HttpPost httpPost = new HttpPost(uri);
  // 使用URL实体转换工具
 UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");         //使用 UrlEncodedFormEntity 来设置 body,消息体内容
            httpPost.setEntity(entityParam);

3、HttpPost两种方式结合在一起请求

    /**
     * 发送 post请求
     */
    public String postParams(PageHelper pageHelper, Long region, String platNum) {
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        ObjectMapper MAPPER = new ObjectMapper();
        try {
            String stringPage = MAPPER.writeValueAsString(pageHelper);
            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            qparams.add(new BasicNameValuePair("region", String.valueOf(region)));
            qparams.add(new BasicNameValuePair("platNum", platNum));
            URI uri = null;
            try {
                uri = URIUtils.createURI("http", "192.168.X.X:23002", -1, "/zyc/get/latestdd",
                        URLEncodedUtils.format(qparams, "UTF-8"), null);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            HttpPost httpPost = new HttpPost(uri);
            System.out.println(httpPost.getURI());     
            // 创建请求参数HttpUriRequest
            List<NameValuePair> list = new LinkedList<>();
            list.add( new BasicNameValuePair("pageHelper",stringPage ));//放在body中
             /*JSONObject postData = new JSONObject();
            postData.put("pageHelper", stringPage);
            httpPost.setEntity(new StringEntity(postData.toString(), HTTP.UTF_8));*/
            // 使用URL实体转换工具
            UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");// UrlEncodedFormEntity  request-body
            httpPost.setEntity(entityParam);
            System.out.println("executing request " + httpPost.getURI());
            // 浏览器表示
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 传输的类型
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        // 打印响应内容
        System.out.println(entityStr);
        return  entityStr;
    }

注:说一下上面用到的BasicNameValuePair方法

三、BasicNameValuePair方法

new BasicNameValuePair(String1,String2)

BasicNameValuePair方法 进行参数传递时,只能使用String这种类型进行传递,事实上表单提交的get和post只能传递String类型,所以如何传递非String类型的参数,比如布尔类型、整型或者实体类。

其实第一个想到的就是将这些符合要求的类型转换成String类型就可以了,但是为什么可以直接转呢?

因为,httpPost.setEntity(new UrlEncodedFormEntity(params));这段神奇的代码

这里放到http entity里面的类型都是字节类型,HTTP协议与FTP,SMTP类似都是通过plain-text ASCII来进行CS数据通信的(不像TCP使用二进制,有历史原因,也更加节约带宽和方便调试),实际上并不存在什么String,Boolean,Integer数据类型,都是通过将byte进行ASCII编码来实现的,服务器端反序列化成String类型后,通过springMVC的框架进行解析,注意这里也需要区分提交方式,框架可能会选取适当的httpMessageConverter进行解析(这个是服务器关注的事情了)

                                            

  • 7
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值