HttpClient之POST调用第三方接口

HttpClient之POST调用第三方接口_第1张图片
http请求

1.坐标依赖


        
            org.apache.httpcomponents
            httpcore
            4.4.10
        
        
            org.apache.httpcomponents
            httpclient
            4.5.6
        

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:[email protected]
 * @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校验成功再进行下一步的请求处理.校验失败则直接拒绝。


HttpClient之POST调用第三方接口_第2张图片
A项目的简易页面



    
    Title
    


Hello Spring Boot Sever! LOCALHOST - ELLIOT

段落one

段落two

段落three

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:[email protected]
 * @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所以在接收到请求之后并没有进行下一步的处理,但是麻雀虽小五脏俱全,交互的逻辑才是需要掌握的核心思想。
本人才疏学浅,如果有什么不对的地方欢迎各位指出,我们可以相互学习.

你可能感兴趣的:(HttpClient之POST调用第三方接口)