HttpClient发送请求和接收参数

1、Client端: 

package com.linxin.jia.HttpClient;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

/*
    <!-- HttpClient依赖 -->
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
    </dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.5</version>
    </dependency>
    <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
    </dependency>
*/
public class Main
{
    public static void main(String[] args)
    {
        TestPost();
        //TestGet();
    }

    private static void TestGet()
    {
        try
        {
            SSLClient client = new SSLClient();

            // get方式的传统传值
            //HttpGet get = new HttpGet("http://localhost:8080/demo/http?st=jiaxin");

            // restful 风格 url
            HttpGet get = new HttpGet("http://localhost:8080/demo/http1/jiaxin");
            get.setHeader("Accept","application/json;charset=utf-8");

            // 此处响应结果值为向上转型得到的值,如果需要获得更多的响应值,可以使用CloseableHttpResponse。
            HttpResponse response = client.execute(get);
            //CloseableHttpResponse response = client.execute(get);
            System.out.println("响应码:"+response.getStatusLine());

            System.out.println("响应body体:"+ EntityUtils.toString(response.getEntity()));
        }
        catch (Exception e)
        {

        }
    }

    private static void TestPost()
    {
        try
        {
            SSLClient client = new SSLClient();
            HttpPost post = new HttpPost("http://localhost:8080/demo/http2");
            post.setHeader("Accept","application/json;charset=utf-8");

            JSONObject params = new JSONObject();
            params.put("name","zhangsan");
            params.put("age","20");
            params.put("address","陕西理工大学");

            // 传值时传递的是json字符串,这样的好处是在服务端无需建立参数模型,直接接收String,便于后期维护。
            StringEntity stringEntity = new StringEntity(params.toJSONString(),"utf-8");
            post.setEntity(stringEntity);

            HttpResponse response = client.execute(post);

            System.out.println("响应码:"+response.getStatusLine());

            System.out.println("响应body体:"+EntityUtils.toString(response.getEntity()));
        }
        catch (Exception e)
        {

        }

    }
}

2、Service侧:

1、针对Spring Boot 时,服务端如何获取通过HttpClient传递的参数值

    @RequestMapping(value = {"/http0"})
    // get方式接收值,?传值
    public Map show0(@RequestParam(required = false) String st)
    {
        System.out.println("st is :"+st);
        JSONObject json = new JSONObject();
        json.put("name","zhangsan");
        json.put("age","20");
        return json;
    }

    @RequestMapping(value = {"/http1/{name}"})
    // get方式接收值,rest 风格
    public Map show1(@PathVariable("name") String st)
    {
        System.out.println("st is :"+st);
        JSONObject json = new JSONObject();
        json.put("name","zhangsan");
        json.put("age","20");
        return json;
    }

    @RequestMapping(value = {"/http2"},method = RequestMethod.POST)
    // 接收body体Json字符串
    public String show2(@RequestBody String st)
    {
        System.out.println("st is :"+st);

        return st;
    }

2、 针对Servlet的形式,如何接收传递的参数

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {

        PrintWriter out= resp.getWriter();

        String paramName = req.getParameter("name");
        String paramAge = req.getParameter("age");

        out.print("paramName = " + paramName +" , paramAge = "+paramAge);
        if (null != out)
        {
            out.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        PrintWriter out= resp.getWriter();
        // 通过流的形式,将请求Body体的数据读取出来。
        InputStream in = req.getInputStream();
        byte[] b = new byte[1024];
        StringBuilder sb = new StringBuilder();
        int len = -1;
        while( -1 != (len =in.read(b)))
        {
            byte[] temp = null;
            temp = Arrays.copyOf(b, len); // 针对最后一次数据读入,防止从流中读入的数据中包含空格。
            sb.append(new String(temp));
        }
        out.print(sb.toString());
        if (null != out)
        {
            out.close();
        }
        if (null != in)
        {
            in.close();
        }
    }
原文地址:https://www.cnblogs.com/nevegiveup/p/9186657.html