HttpClient之POST调用第三方接口

http请求

1.坐标依赖

<!--HttpClient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

2.分析

在日常开发中,我们可能会去对接一些第三方的接口,亦或者是在一个项目中对接另外一个项目.这样类似的情况都会牵涉到数据交互的问题,所以我们就可以模拟用户在浏览器上的行为发送Http请求来完成数据的交互

3.A项目发送请求

package lp.elliot.controller;

import com.alibaba.fastjson.JSON;
import lp.elliot.pojo.ElliotResponse;
import lp.elliot.pojo.Info;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * @Author:Elliot
 * @Email:elliot_mr@126.com
 * @Date:2019/3/20 22:59
 * @Description:
 * @Version 1.011
 */
@Controller
@RequestMapping("/http")
public class HttpController {

    @RequestMapping("/send")
    @ResponseBody
    public ElliotResponse sendInfo(@RequestBody Info info) throws IOException, URISyntaxException {
        System.out.println(info);
        //httpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //post对象
        HttpPost httpPost = new HttpPost("http://10.9.1.55:8090/http/send2");
        //请求体格式
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("token","lpck");
        String charSet = "UTF-8";
        Info newInfo = new Info();
        newInfo.setOne(info.getOne());
        newInfo.setTwo(info.getTwo());
        newInfo.setThree(info.getThree());
        //请求参数JSON序列化
        String jsonInfo = JSON.toJSONString(newInfo);
        StringEntity entity = new StringEntity(jsonInfo, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            //响应状态码为200
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                System.out.println(jsonString);
                return ElliotResponse.ok(200,jsonString);
            }
            else{
                return ElliotResponse.ok(500,"请求失败!");
            }
        }
        //资源释放
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

关于Header中的Token

这里的自定义token的目的在于对接的时候作为一个密钥校验 如果token校验成功再进行下一步的请求处理.校验失败则直接拒绝。


A项目的简易页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../static/res/js/jquery-3.3.1.min.js"></script>
</head>
<body>
<h1>Hello Spring Boot Sever! LOCALHOST - ELLIOT</h1>
<p id="one">段落one</p>
<p id="two">段落two</p>
<p id="three">段落three</p>
<input type="button" value="提交数据到另一个项目" id="submit">
</body>
<script type="text/javascript">
    $("#submit").click(function () {
        var one = $("#one").text();
        var two = $("#two").text();
        var three = $("#three").text();
        $.ajax({
            type:'POST',
            url:'/http/send',
            contentType: "application/json;charset=UTF-8",
            data:JSON.stringify({
                "one":one,
                "two":two,
                "three":three
            }),
            dataType:'json',
            timeout:5000,
            success:function (response) {
                if (response.msg.code == 200){
                    window.confirm("success!");
                }
              if (response.msg.code == 500){
                    window.confirm("token校验失败!");
                }
            }
        })
    })
</script>
</html>

4.B项目接收请求并交互

import cn.lpck.xdfds.pojo.BaseResponse;
import cn.lpck.xdfds.pojo.Info;
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 org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;

/**
 * @Author:Elliot
 * @Email:elliot_mr@126.com
 * @Date:2019/3/20 17:26
 * @Description:
 * @Version 1.011
 */
@RestController
@RequestMapping("/http")
public class HttpController {

    @RequestMapping("/send2")
    public BaseResponse sendInfo(@RequestBody Info info, HttpServletRequest request) throws IOException {

        System.out.println(info);
        String utoken = request.getHeader("token");
        System.out.println(utoken);
        if ("lpck".equals(utoken)){
            return BaseResponse.ok(200,"Success");
        }else {
            return BaseResponse.ok(500,"Token错误!");
        }
    }
    
}

因为这里只是写了一个简易的Demo所以在接收到请求之后并没有进行下一步的处理,但是麻雀虽小五脏俱全,交互的逻辑才是需要掌握的核心思想。
本人才疏学浅,如果有什么不对的地方欢迎各位指出,我们可以相互学习.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容