请求第三方接口,请求和接收参数

-------------------------------------A:服务器发出请求-------------------------------------

@RequestMapping("/portal")
@ResponseBody
public String getTest(@RequestBody PortalVo pvo){
   String interfacet = pvo.getInterfacet();
   String data = pvo.getData();
   String url = "http://127.0.0.1:10082/security/initDataByNums";
   Map<String,Object> maps = ThirdPartyInterfaceUtils.getExternalInfo(url,data);
   return maps.toString();
}

-------------------------------------Postman post请求-------------------------------------

{

    "interfacename":"1",

    "data":"{'aa':'111','aa2':'111','aa3':'111'}"

}

{

    "interfacename":"1",

    "data""{\"aa\" : \"张三\"}"

}

-------------------------------------PortalVo 实体类-------------------------------------

private String interfacet;

Private String data;

-------------------------------------工具类-------------------------------------

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ThirdPartyInterfaceUtils {
    /**
     * 调取外系统接口的数据
     * @param date
     * @return
     */
    public static Map<String,Object> getExternalInfo(String infoUrl, String date){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            //配置超时时间
            RequestConfig requestConfig = RequestConfig.custom().
                    setConnectTimeout(300000).setConnectionRequestTimeout(300000)
                    .setSocketTimeout(300000).setRedirectsEnabled(true).build();
            HttpPost httpPost = new HttpPost(infoUrl);
            httpPost.headset("content-type", "application/x-www-form-urlencoded;catharses=UTF-8");
            //设置超时时间
            httpPost.setConfig(requestConfig);
            //装配post请求参数
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            list.add(new BasicNameValuePair("date",date));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            //设置post求情参数
            httpPost.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String resData = EntityUtils.toString(httpEntity);
            System.out.println("返回信息 =======" + resData);
            JSONObject o = JSONObject.parseObject(resData);
            Map<String,Object> map = new HashMap<>();
            map = o;
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

-------------------------------------Maven-------------------------------------

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.10</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

-------------------------------------B 接收端,接收a请求-------------------------------------

@RequestMapping("/initDataByNums")
@ResponseBody
public Map<String,String> initDataByNums(HttpServletRequest request) {
   String pa = "";
   JSONObject jsonObject = null;
   try {
      InputStream in = request.getInputStream();
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      byte[] b = new byte[1024 * 8];
      int len;
      while ((len = in.read(b)) != -1){
         byteArrayOutputStream.write(b, 0, len);
      }
      pa = new String(byteArrayOutputStream.toByteArray());//拿到值
      pa = URLDecoder.decode(pa, "utf-8");//去掉符号,中文乱码
      pa = pa.substring(5,pa.length());//去掉data={}
      pa = pa.replaceAll("=",":");//等号换冒号
      jsonObject = JSONObject.fromObject(pa);
   } catch (IOException e) {
      e.printStackTrace();
   }
   System.out.println(jsonObject.get("aa"));//接收到了
   Map map1 = new HashMap();//假设一个返回值
   map1.put("aaa","unifiedEntrance");
   return map1;
}

(function(){ //定义外部接口 //Request开放接口给外部,提供两个接口:getParameter和getParameterValues //这样外部的JavaScript文件就可以通过调用Request.getParameter()来执行相应的动作 Request = { getParameter:getParameter, getParameterValues:getParameterValues }; //得到URL后的参数,例如URL:http://abc?x=1&y=2 //那么getParameter("x") 得到1 function getParameter(paraName,wnd) { //如果不提供wnd参数,则默认为当前窗口 if(wnd == null) wnd = self; //得到地址栏上“?”后边的字符串 var paraStr = wnd.location.search.slice(1); //根据“&”符号分割字符串 var paraList = paraStr.split(/\&/g); for (var i = 0; i < paraList.length; i++) { //用正则表达式判断字符串是否是“paraName=value”的格式 //关于正则表达式的内容在本书的第10章中有较详细的讨论 var pattern = new RegExp("^"+paraName+"[?=\\=]","g"); if(pattern.test(paraList[i])) { //若是,则返回解码后的value的内容 return decodeURIComponent(paraList[i].split(/\=/g)[1]); } } } //如果有多个重复的paraName的情况下,下面这个方法返回一个包含了所有值的数组 //例如http://abc?x=1&x=2&x=3 ,getParameterValues("x")得到[1,2,3] function getParameterValues(paraName,wnd) { if(wnd == null) wnd = self; var paraStr = wnd.location.search.slice(1); var paraList = paraStr.split(/\&/g); var values = new Array(); for (var i = 0; i < paraList.length; i++) { //上面的判断部分和getParameter()方法类似 //区别是对应每一个paramName的value有多个 var pattern = new RegExp("^"+paraName+"[?=\\=]","g"); if(pattern.test(paraList[i])) { //将所有满足paramName=value的结果的value都放入一个数组中 values.push(decodeURIComponent(paraList[i].split(/\=/g)[1])); } } //返回结果数组 return values; } })(); 输出如下: <script type="text/javascript" src="客户端模拟服务器端的Request发送和获得参数.js"></script> <script> document.write(Request.getParameter("a")) document.write("<br/>"+document.URL) </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值