HttpClient之POST調(diào)用第三方接口

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.分析

在日常開發(fā)中,我們可能會去對接一些第三方的接口,亦或者是在一個項目中對接另外一個項目.這樣類似的情況都會牽涉到數(shù)據(jù)交互的問題,所以我們就可以模擬用戶在瀏覽器上的行為發(fā)送Http請求來完成數(shù)據(jù)的交互

3.A項目發(fā)送請求

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());
        //請求參數(shù)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();
            //響應(yīng)狀態(tài)碼為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();
            }
        }
    }

}

關(guān)于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="提交數(shù)據(jù)到另一個項目" 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所以在接收到請求之后并沒有進行下一步的處理,但是麻雀雖小五臟俱全,交互的邏輯才是需要掌握的核心思想。
本人才疏學(xué)淺,如果有什么不對的地方歡迎各位指出,我們可以相互學(xué)習(xí).

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容