httpClient與OkHttpclient傳輸POST請求,請求頭加密,請求引數為實體物件

2020-10-03 16:00:34

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();
        }
    }
}