设置请求头、参数(字节流写入)
public static void main(String[] args) {
CloseableHttpResponse response=null;
String entityStr = null;
String url ="https://";
CloseableHttpClient httpClient= HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url3);
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
httpPost.addHeader("publicKey", publicKey);
httpPost.addHeader("reqid", reqid);
String stringDate = SimpleDateFormatUtils.getStringDate(new Date(), SimpleDateFormatUtils.PATTERN_TYPE_3);
httpPost.addHeader("reqtime", stringDate);
JSONObject jsonObject = new JSONObject();
jsonObject.put("year", "2021");
String s = JSON.toJSONString(jsonObject);
BasicHttpEntity httpEntity = new BasicHttpEntity();
httpEntity.setContent(new BufferedServletInputStream(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8)));
httpPost.setEntity(httpEntity);
String paramStr = s + "|" + reqid + "|" + stringDate + "|" + publicKey + "|" + privateKey;
System.out.println("加密前字符串:" + paramStr);
String resultHexString = SmRsaUtils.encrypt(paramStr, publicKey);
System.out.println("加密后字符串:" + resultHexString);
httpPost.addHeader("sign", resultHexString);
httpPost.addHeader("User-Agent:", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36");
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
int code =response.getStatusLine().getStatusCode();
System.out.println("StatusCode: " + code);
Assert.assertEquals(200,code);
String result= EntityUtils.toString(entity,"UTF-8");
System.out.println("接口返回结果是:="+result);
}catch(Exception e){
e.printStackTrace();
}finally {
try {
if(httpClient!=null) {
httpClient.close();
}
if (response!=null){
response.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
发送json格式的参数
public static void main(String[] args) {
CloseableHttpResponse response=null;
String entityStr = null;
String url ="https://";
CloseableHttpClient httpClient= HttpClients.createDefault();
HttpPost httpPost=new HttpPost(url);
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
httpPost.addHeader("User-Agent:","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36");
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("id","122551");
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString());
httpPost.setEntity(stringEntity);
response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
int code =response.getStatusLine().getStatusCode();
System.out.println("StatusCode: " + code);
Assert.assertEquals(200,code);
entityStr= EntityUtils.toString(entity,"UTF-8");
System.out.println("接口返回结果是:="+entityStr);
}catch(Exception e){
e.printStackTrace();
}finally {
try {
if(httpClient!=null) {
httpClient.close();
}
if (response!=null){
response.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
|