使用httpClient訪問https遠程服務器調用遠程接口並且傳遞參數以及忽略SSL證書的問題
首先寫一個httpClient主要調用遠程API和參數傳遞
import com.hxsj.inspection.common.util.SSLClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* @program: inspection-project
* @description: 使用httpClient訪問遠程api
* @author: Chai.duolai
* @create: 2019-04-15 16:19
**/
@RequestMapping("httpClient")
@RestController
public class HttpClients {
@PostMapping("/postNoArguments")
public String postNoArguments() throws Exception {
//以下是我自己調用的接口需要傳遞的參數
Random random=new Random();
String accesskey="xxx";
//獲得一個隨機數
String nonce = String.valueOf(random.nextInt());
//獲得一個時間戳
String timestamp = String.valueOf(System.currentTimeMillis());
StringBuffer stringBuffer=new StringBuffer();
String secretkey="xxx";
//將上面的三個參數按照順序合併成一個字符串
String signaturee = stringBuffer.append(secretkey).append(nonce).append(timestamp).toString();
//在這裏我要調用的api傳遞的第四個參數需要計算它的SHA1值(40位的)
String signature= sha1(signaturee);
//這裏就是你要訪問的具體地址了,填你自己的
String url = "https://IP地址/api/token";
//創建 MultipartEntityBuilder,以此來構建我們的參數
MultipartEntityBuilder EntityBuilder = MultipartEntityBuilder.create();
//設置字符編碼,防止亂碼
ContentType contentType= ContentType.create("text/plain", Charset.forName("UTF-8"));
//填充我們的文本內容,這裏相當於input 框中的 name 與value
EntityBuilder.addPart("accesskey", new StringBody(accesskey,contentType));
EntityBuilder.addPart("nonce", new StringBody(nonce,contentType));
EntityBuilder.addPart("timestamp", new StringBody(timestamp,contentType));
EntityBuilder.addPart("signature", new StringBody(signature,contentType));
CloseableHttpClient httpClient =null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
//在這裏必須強調一點的是,看你調用的接口需要的參數格式是什麼
//我這裏接口的參數格式是form-data類型的,如果你需要傳值json或者別的類型我在下面會寫到,別急
// httpPost.addHeader("Content-Type", "application/json");
/*StringEntity se = new UrlEncodedFormEntity(formList, "utf-8");
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));*/
httpPost.setEntity(EntityBuilder.build());
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,"UTF-8");
System.out.println("響應內容爲"+result);
}
}
}catch(Exception ex){
ex.printStackTrace();
}finally {
//在這裏強調一下httpClient一定要關閉。不然會出錯
httpClient.close();
}
return result;
}
在代碼中我有說到我的第四個參數需要計算SHA1的值,下面代碼可以參考
public static String sha1(String data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(data.getBytes());
StringBuffer buf = new StringBuffer();
byte[] bits = md.digest();
for(int i=0;i<bits.length;i++){
int a = bits[i];
if(a<0) a+=256;
if(a<16) buf.append("0");
buf.append(Integer.toHexString(a));
}
return buf.toString();
}
標題:由於本人也是第一次,所以嘗試了很多坑,希望看到這篇博客的人可以幫到你
剛在在代碼中說到了調用api傳不同格式的參數問題,我看了一篇博客寫的很好,你們可以根據它的改一下就好,我的參數是form-data方式格式的,當然了還有json類型的
插入鏈接:http://www.cnblogs.com/iscys/p/9595358.html 可以看看他的傳遞參數
接下來就是處理SSL證書的問題,第一次遇到,當時請教了很多人,這個我也是看了一篇博客的,如有侵權,望告知刪除
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* @program: inspection-project
* @description: 忽略安全證書
* @author: Chai.duolai
* @create: 2019-04-16 09:56
**/
public class SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
- 本人的郵箱[email protected] 如果有什麼問題或者學術交流,很願意和你一起探討,可以把微信給你發送過去