httpclient ajax post,HttpClient之POST调用第三方接口

7e28c48de266?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

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

7e28c48de266?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

A项目的简易页面

Title

Hello Spring Boot Sever! LOCALHOST - ELLIOT

段落one

段落two

段落three

$("#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校验失败!");

}

}

})

})

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所以在接收到请求之后并没有进行下一步的处理,但是麻雀虽小五脏俱全,交互的逻辑才是需要掌握的核心思想。

本人才疏学浅,如果有什么不对的地方欢迎各位指出,我们可以相互学习.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值