httpClient and OkHttpclient transmit POST requests, the request header is encrypted, and the request parameters are entity objects

1. Realistic needs:

Outsourcing requires us to call Ctrip's interface

2. Problem description:

Get can, but post can't

3. The problem is finally solved:

Going back and looking at the document, I found that the previous test interface is still used, but this post interface will change a URL in the production environment, that is, the proxy server requirements change, for example, http://a.com used before, now it is changed to http ://a.vip.com, it will only be open to merchants who signed the contract. Damn, I forgot that I also signed the contract. I forgot about this environmental issue.

4. Additional requirements:

Able to pass a fixed time format

5. Interface call requirements:

1. This interface is provided for distributors to access, and the request return parameters are all in Json format.
2. Request interface Url uniform parameters: AID (distributor ID), SID (distributor account ID) Example: http://apiproxy.fws .ctripqa.com/apiproxy/soa2/13429/getHotelList?AID=1&SID=50

3. Request header parameters: timestamp timestamp (for example: 1521715473339, current time <30 seconds, unit: ms) interfacekey key
requesttype interface name (see the table below, the corresponding interface corresponds to RequestType) signature MD5 encrypted string hoteltype 3
(fixed Value, only for transparent transmission, do not transmit for non-transparent hotels, the hotelid in transparent transmission mode is the parent hotel id)
masterhotelmode T or F (only for landing mode, if T is transmitted, the landing mode data is aggregated to the parent hotel dimension, the interface in the document is involved The hotelId is replaced with the parent hotel id)
encryption logic: signature=Md5(timestamp+AID+MD5(interfacekey).toUpperCase()+SID+RequestType)
.toUpperCase() Remarks: 1), "Agent through distribution interface" supports Http For interaction, the request header parameter names are uniformly lowercased and passed into httpHeader for interactive processing.
2). Pass "hoteltype=3", only return the transparent hotel data, please mark it yourself after fetching the number, the field must be transmitted when the transparent transmission hotel calls all interfaces of the distribution; non-transparent hotels do not transmit this field (non-transparent hotels Request that the old interface remains unchanged).

6. Solution:

The first type: 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);
    }
}

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

Guess you like

Origin blog.csdn.net/weixin_43404791/article/details/108899578
Recommended