httpClient与OkHttpclient传输POST请求,请求头加密,请求参数为实体对象

1. 现实需求:

外包需要我们调用携程的接口

2. 问题描述:

get可以, 但是post就不行

3. 问题最终解决:

回去看文档, 发现还是再用之前的测试接口, 但是这个post接口在生产环境会变换一个网址, 也就是代理服务器要求变, 比如说以前是用的http://a.com, 现在改为http://a.vip.com, 只会开放给签署合同的商家, 妈的我忘了我也是签约了的, 这个环境问题全都忘掉了

4. 额外需求:

能够传递固定的时间格式

5. 接口调用需求:

1、此接口为分销商接入提供,请求返回参数均为Json格式内容
2、请求接口Url统一参数:AID(分销商ID)、SID(分销商账号ID)例:http://apiproxy.fws.ctripqa.com/apiproxy/soa2/13429/getHotelList?AID=1&SID=50

3、请求头参数: timestamp 时间戳(例:1521715473339,当前时间<30秒,单位:ms) interfacekey 密钥
requesttype 接口名(见见下表,对应接口传对应RequestType) signature MD5加密串 hoteltype 3
(固定值,透传专用,非透传酒店不要传,透传模式hotelid均为母酒店id)
masterhotelmode T或F(落地模式专用,若传T,落地模式数据聚合至母酒店维度,文档中接口所涉及的hotelId均替换为母酒店id)
加密逻辑:signature=Md5(timestamp+AID+MD5(interfacekey).toUpperCase()+SID+RequestType)
.toUpperCase() 备注: 1)、“代理通分销接口”支持Http交互,请求头参数名统一小写,传入httpHeader交互处理。
2)、传“hoteltype=3”,仅返回透传酒店数据,取数后请自行做标记,透传酒店调用分销所有接口必传该字段;非透传酒店不要传该字段(非透传酒店请求旧版接口保持不变)。

6. 解决方案:

第一种 : okHttpClient

package cn.hctech2006.reptile1.bean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import okhttp3.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.util.DigestUtils;

import util.DateTimeUtil;

import java.io.IOException;
import java.net.StandardSocketOptions;
import java.util.Date;
import java.util.Map;

public class OkHttpClientTest {


    public OkHttpClientTest() throws IOException {
    }

    public static void main(String[] args) throws IOException {
        Param param = new Param();
        SearchCandidate searchCandidate = new SearchCandidate();
        DateTimeRange dateTimeRange = new DateTimeRange();
        PagingSettings pagingSettings = new PagingSettings();
        pagingSettings.setPageSize(1000);
        pagingSettings.setLastRecordId("0");
        dateTimeRange.setStart(DateTimeUtil.strToDate("2020-09-01 17:23:00"));
        dateTimeRange.setEnd(DateTimeUtil.strToDate("2020-09-01 17:53:00"));
        searchCandidate.setCityID(1);
        searchCandidate.setCountryID(1);
        searchCandidate.setDateTimeRange(dateTimeRange);
        param.setSearchCandidate(searchCandidate);
        param.setPagingSettings(pagingSettings);
        String jsonString = JSON.toJSONStringWithDateFormat(param,"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
        String  timestamp = String.valueOf(System.currentTimeMillis());
         int AID=xxx;
        int SID=xxx;
        String requestType =  "GET_STATICINFO_CHANGE";
        String interfaceKey = "15456a8b-f9b3-4e39-83cf-7186b9cb6336";
        String interfaceKeyMD5 = DigestUtils.md5DigestAsHex(interfaceKey.getBytes());
        System.out.println("interfaceKeyMD5: "+interfaceKeyMD5);
        String signature = DigestUtils.md5DigestAsHex((timestamp+AID+"1382C3AAA6AEF5F416832EB93F906131"+SID+requestType).getBytes()).toUpperCase();
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\n\t\"searchCandidate\":{\n\t\t\"dateTimeRange\":{\n\t\t\t\"start\": \"2020-09-01 17:23:00\",\n\t\t\t\"end\": \"2020-09-01 17:53:00\"\n\t\t},\n\t\t\"cityID\": 1,\n\t\t\"countryID\": 1\n\t},\n\t\"pagingSettings\":{\n\t\t\"lastRecordId\": \"0\",\n\t\t\"pageSize\": 1000\n\t}\n}");
        RequestBody body1 = RequestBody.create(mediaType, jsonString);
        Request request = new Request.Builder()
                .url("http://allianceapi.vipdlt.com/apiproxy/soa2/13429/getstaticinfochange?AID=xxx&SID=xxx")
                .post(body1)
                .addHeader("timestamp", timestamp)
                .addHeader("interfacekey", "15456a8b-f9b3-4e39-83cf-7186b9cb6336")
                .addHeader("signature", signature)
                .addHeader("requesttype", "GET_STATICINFO_CHANGE")
                .addHeader("content-type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();

        Response response = client.newCall(request).execute();
        System.out.println("response.message: "+response.message());
        //System.out.println("response.message: "+response.body().string());
        byte[] b = response.body().bytes(); //获取数据的bytes
        String info = new String(b, "UTF-8"); //然后将其转为gb2312
        System.out.println(info);
    }
}

第二种 HttpClient

package cn.hctech2006.reptile1;

import cn.hctech2006.reptile1.bean.DateTimeRange;
import cn.hctech2006.reptile1.bean.PagingSettings;
import cn.hctech2006.reptile1.bean.Param;
import cn.hctech2006.reptile1.bean.SearchCandidate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;
import util.DateTimeUtil;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class HttpClientTestPOst {
    public static void main(String[] args) throws IOException {
        //初始化httpContext
        HttpContext httpContext = new BasicHttpContext();

        Param param = new Param();
        SearchCandidate searchCandidate = new SearchCandidate();
        DateTimeRange dateTimeRange = new DateTimeRange();
        PagingSettings pagingSettings = new PagingSettings();
        pagingSettings.setPageSize(1000);
        pagingSettings.setLastRecordId("0");
        dateTimeRange.setStart(DateTimeUtil.strToDate("2018-07-13 20:40:00"));
        dateTimeRange.setEnd(DateTimeUtil.strToDate("2018-07-13 20:50:00"));
        searchCandidate.setCityID(1);
        searchCandidate.setCountryID(1);
        searchCandidate.setDateTimeRange(dateTimeRange);
        param.setSearchCandidate(searchCandidate);
        param.setPagingSettings(pagingSettings);
        String jsonString = JSON.toJSONStringWithDateFormat(param,"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
        String personUrl = "http://allianceapi.vipdlt.com/apiproxy/soa2/13429/getstaticinfochange?AID=109&SID=104";
        //第三种方式

        HttpPost httpGetStr = new HttpPost(personUrl);

        String  timestamp = String.valueOf(System.currentTimeMillis());
        int AID=xxx;
        int SID=xxx;
        String requestType =  "GET_STATICINFO_CHANGE";
        String interfaceKey = "15456a8b-f9b3-4e39-83cf-7186b9cb6336";
        String interfaceKeyMD5 = DigestUtils.md5DigestAsHex(interfaceKey.getBytes());
        System.out.println("interfaceKeyMD5: "+interfaceKeyMD5);
        String signature = DigestUtils.md5DigestAsHex((timestamp+AID+"1382C3AAA6AEF5F416832EB93F906131"+SID+requestType).getBytes()).toUpperCase();
        httpGetStr.setHeader("timestamp", timestamp);
        httpGetStr.setHeader("signature", signature);
        httpGetStr.setHeader("requesttype", "GET_STATICINFO_CHANGE");
        httpGetStr.setHeader("interfacekey", "15456a8b-f9b3-4e39-83cf-7186b9cb6336");
        httpGetStr.setHeader("content-type", "application/json");
        //httpGetStr.setHeader("cache-control", "no-cache");
        System.out.println("signature: "+signature);
        System.out.println("timestamp: "+timestamp);
        HttpClient httpClient = HttpClients.custom().build();
        StringEntity entity = new StringEntity(jsonString);

        InputStream io = entity.getContent();
        BufferedInputStream bio = new BufferedInputStream(io);
        byte[] buf = new byte[1024];
        int len = 0;
        System.out.println("entity: ");
        while ((len=bio.read(buf)) != -1) System.out.println(new String(buf, 0, len));
        bio.close();

        httpGetStr.setEntity(entity);
        entity.setContentType("application/json");

        try {
            HttpResponse response = httpClient.execute(httpGetStr, httpContext);
            //获取具体响应信息
            System.out.println("response: "+response.getStatusLine());
            HttpEntity httpEntity =response.getEntity();
            String entity1 = EntityUtils.toString(httpEntity, "gbk");
            System.out.println("entity: "+entity1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

©️2020 CSDN 皮肤主题: 黑客帝国 设计师:上身试试 返回首页