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();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM