javahttps
Ⅰ 用java代碼發生請求https,發生異常!
因為你的異常不是能必定復現的,有時發生,又有時不發生,那麼只能初步的認為是網路連接不穩定造成的
如果想徹底查清問題所在,只能通過網路抓包工具,在復現問題時查看網路通信包,看看到底是網路連接報的錯誤還是代碼邏輯報的錯誤
另外,Remote host closed connection ring handshake這個異常在客戶端/服務端的TLS版本不一致時也會拋出,你可以嘗試在發送請求前在代碼中設置TLS版本和服務端一致後在發送請求,相關問題和解決方案stackoverflow上能查到很多
Ⅱ 如何配置Java HTTPS CA證書
Java使用的伺服器環境是:Tomcat,安裝HTTPS是根據:Tomcat環境安裝的。
Tomcat 安裝SSL證書:https://www.gworg.com/ssl/109.html
tomcat 自動跳轉到HTTPS:https://www.gworg.com/ssl/132.html
注意:安裝防火牆需要設置允許443埠或關閉防火牆,如果本地伺服器安裝安全狗的,請允許443埠。該證書文件後綴.jks,安裝需要證書密碼,沒有的話需要淘寶Gworg獲取證書。
Ⅲ 如何在java中發起http和https請求
1.寫http請求方法
[java] view plain
//處理http請求 requestUrl為請求地址 requestMethod請求方式,值為"GET"或"POST"
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
URL url=new URL(requestUrl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往伺服器端寫內容 也就是發起http請求需要帶的參數
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//讀取伺服器端返回的內容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
2.測試。
[java] view plain
public static void main(String[] args){
String s=httpRequest("http://www.qq.com","GET",null);
System.out.println(s);
}
輸出結果為www.qq.com的源代碼,說明請求成功。
註:1).第一個參數url需要寫全地址,即前邊的http必須寫上,不能只寫www.qq.com這樣的。
2).第二個參數是請求方式,一般介面調用會給出URL和請求方式說明。
3).第三個參數是我們在發起請求的時候傳遞參數到所要請求的伺服器,要傳遞的參數也要看介面文檔確定格式,一般是封裝成json或xml.
4).返回內容是String類,但是一般是有格式的json或者xml。
二:發起https請求。
1.https是對鏈接加了安全證書SSL的,如果伺服器中沒有相關鏈接的SSL證書,它就不能夠信任那個鏈接,也就不會訪問到了。所以我們第一步是自定義一個信任管理器。自要實現自帶的X509TrustManager介面就可以了。
[java] view plain
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
註:1)需要的包都是java自帶的,所以不用引入額外的包。
2.)可以看到裡面的方法都是空的,當方法為空是默認為所有的鏈接都為安全,也就是所有的鏈接都能夠訪問到。當然這樣有一定的安全風險,可以根據實際需要寫入內容。
2.編寫https請求方法。
[java] view plain
/*
* 處理https GET/POST請求
* 請求地址、請求方法、參數
* */
public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
//創建SSLContext
SSLContext sslContext=SSLContext.getInstance("SSL");
TrustManager[] tm={new MyX509TrustManager()};
//初始化
sslContext.init(null, tm, new java.security.SecureRandom());;
//獲取SSLSocketFactory對象
SSLSocketFactory ssf=sslContext.getSocketFactory();
URL url=new URL(requestUrl);
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
//設置當前實例使用的SSLSoctetFactory
conn.setSSLSocketFactory(ssf);
conn.connect();
//往伺服器端寫內容
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//讀取伺服器端返回的內容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
可見和http訪問的方法類似,只是多了SSL的相關處理。
3.測試。先用http請求的方法訪問,再用https的請求方法訪問,進行對比。
http訪問:
[java] view plain
public static void main(String[] args){
String s=httpRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
結果為:
https訪問:
[java] view plain
public static void main(String[] args){
String s=httpsRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
結果為:
可見https的鏈接一定要進行SSL的驗證或者過濾之後才能夠訪問。
三:https的另一種訪問方式——導入服務端的安全證書。
1.下載需要訪問的鏈接所需要的安全證書。https://kyfw.12306.cn/ 以這個網址為例。
1)在瀏覽器上訪問https://kyfw.12306.cn/。
2)點擊上圖的那個打了×的鎖查看證書。
3)選擇復制到文件進行導出,我們把它導入到java項目所使用的jre的lib文件下的security文件夾中去,我的是這個路徑。D:\Program Files (x86)\Java\jre8\lib\security
註:中間需要選導出格式,就選默認的就行,還需要命名,我命名的是12306.
2.打開cmd,進入到java項目所使用的jre的lib文件下的security目錄。
3.在命令行輸入 Keytool -import -alias 12306 -file 12306.cer -keystore cacerts
4.回車後會讓輸入口令,一般默認是changeit,輸入時不顯示,輸入完直接按回車,會讓確認是否信任該證書,輸入y,就會提示導入成功。
5.導入成功後就能像請求http一樣請求https了。
測試:
[java] view plain
public static void main(String[] args){
String s=httpRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
結果:
現在就可以用http的方法請求https了。
註:有時候這一步還是會出錯,那可能是jre的版本不對,我們右鍵run as——run configurations,選擇證書所在的jre之後再運行。
Ⅳ 如何配置Java HTTPS CA證書
這個很復雜(反正我配置了幾次都失敗了,而且本地(windows)就算配置成功了,線上又水土不服(Linux)),所以,我一般都是用httpclient封裝一個工具類,然後繞過https證書驗證,直接發送https請求,至於怎麼封裝,網上例子很多
Ⅳ 如何在java中發起http和https請求
1.寫http請求方法
[java] view plain
//處理http請求 requestUrl為請求地址 requestMethod請求方式,值為"GET"或"POST"
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
URL url=new URL(requestUrl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往伺服器端寫內容 也就是發起http請求需要帶的參數
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//讀取伺服器端返回的內容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
Ⅵ java 建立雙向認證 https連接
絕對好用的。直用的這個,GOOD LUCK FOR YOU
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 創建SSLContext對象,並使用我們指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 從上述SSLContext對象中得到SSLSocketFactory對象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 設置請求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 當有數據需要提交時
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意編碼格式,防止中文亂碼
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 將返回的輸入流轉換成字元串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
System.out.println("返回的數據:"+buffer.toString());
// jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return buffer.toString();
}
Ⅶ 如何用JAVA實現HTTPS客戶端
import java.io.*;
import java.net.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
public class TrustSSL {
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static void main(String[] args) throws Exception {
InputStream in = null;
OutputStream out = null;
byte[] buffer = new byte[4096];
String str_return = "";
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
URL console = new URL(
"https://192.168.1.188/test.php?username=測試");
HttpsURLConnection conn = (HttpsURLConnection) console
.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
DataInputStream indata = new DataInputStream(is);
String ret = "";
while (ret != null) {
ret = indata.readLine();
if (ret != null && !ret.trim().equals("")) {
str_return = str_return
+ new String(ret.getBytes("ISO-8859-1"), "GBK");
}
}
conn.disconnect();
} catch (ConnectException e) {
System.out.println("ConnectException");
System.out.println(e);
throw e;
} catch (IOException e) {
System.out.println("IOException");
System.out.println(e);
throw e;
} finally {
try {
in.close();
} catch (Exception e) {
}
try {
out.close();
} catch (Exception e) {
}
}
System.out.println(str_return);
}
}
Ⅷ 如何使用JAVA請求HTTPS
//處理http請求requestUrl為請求地址requestMethod請求方式,值為"GET"或"POST"
publicstaticStringhttpRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){
StringBufferbuffer=null;
try{
URLurl=newURL(requestUrl);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往伺服器端寫內容也就是發起http請求需要帶的參數
if(null!=outputStr){
OutputStreamos=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//讀取伺服器端返回的內容
InputStreamis=conn.getInputStream();
InputStreamReaderisr=newInputStreamReader(is,"utf-8");
BufferedReaderbr=newBufferedReader(isr);
buffer=newStringBuffer();
Stringline=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exceptione){
e.printStackTrace();
}
returnbuffer.toString();
}
Ⅸ https怎麼用java進行訪問
沒有證書認證的,如果想訪問支付寶等,需要配置一個訪問的公鑰
public class HttpClient {
private String charset = "UTF-8";
private boolean safe = false;
private String url;
Map<String, String> headers = null;
public HttpClient(String url) {
this.url = url;
...
public String post(String httpStr) throws IOException {
if (this.safe) {
return this.sendhttpsReq("POST", "", headers);
.....
while ((byteread = in.read(buf)) != -1) {
result.append(buf, 0, byteread);
}
....
conn.setRequestMethod(method);
conn.setDoOutput(true);
}
});
conn.setRequestProperty("Content-Type", "text/html");
.....
}
StringBuilder result = new StringBuilder(100);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private static c
Ⅹ 求解java怎樣發送https請求
使用httpClient可以發送,具體的可以參考下面的代碼
SSLClient類,繼承至HttpClient
importjava.security.cert.CertificateException;
importjava.security.cert.X509Certificate;
importjavax.net.ssl.SSLContext;
importjavax.net.ssl.TrustManager;
importjavax.net.ssl.X509TrustManager;
importorg.apache.http.conn.ClientConnectionManager;
importorg.apache.http.conn.scheme.Scheme;
importorg.apache.http.conn.scheme.SchemeRegistry;
importorg.apache.http.conn.ssl.SSLSocketFactory;
importorg.apache.http.impl.client.DefaultHttpClient;
//用於進行Https請求的HttpClient
{
publicSSLClient()throwsException{
super();
SSLContextctx=SSLContext.getInstance("TLS");
X509TrustManagertm=newX509TrustManager(){
@Override
publicvoidcheckClientTrusted(X509Certificate[]chain,
StringauthType)throwsCertificateException{
}
@Override
publicvoidcheckServerTrusted(X509Certificate[]chain,
StringauthType)throwsCertificateException{
}
@Override
publicX509Certificate[]getAcceptedIssuers(){
returnnull;
}
};
ctx.init(null,newTrustManager[]{tm},null);
SSLSocketFactoryssf=newSSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManagerccm=this.getConnectionManager();
SchemeRegistrysr=ccm.getSchemeRegistry();
sr.register(newScheme("https",443,ssf));
}
}
HttpClient發送post請求的類
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Map.Entry;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
/*
*利用HttpClient進行post請求的工具類
*/
publicclassHttpClientUtil{
publicStringdoPost(Stringurl,Map<String,String>map,Stringcharset){
HttpClienthttpClient=null;
HttpPosthttpPost=null;
Stringresult=null;
try{
httpClient=newSSLClient();
httpPost=newHttpPost(url);
//設置參數
List<NameValuePair>list=newArrayList<NameValuePair>();
Iteratoriterator=map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String>elem=(Entry<String,String>)iterator.next();
list.add(newBasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size()>0){
UrlEncodedFormEntityentity=newUrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponseresponse=httpClient.execute(httpPost);
if(response!=null){
HttpEntityresEntity=response.getEntity();
if(resEntity!=null){
result=EntityUtils.toString(resEntity,charset);
}
}
}catch(Exceptionex){
ex.printStackTrace();
}
returnresult;
}
}
測試代碼
importjava.util.HashMap;
importjava.util.Map;
//對介面進行測試
publicclassTestMain{
privateStringurl="https://192.168.1.101/";
privateStringcharset="utf-8";
=null;
publicTestMain(){
httpClientUtil=newHttpClientUtil();
}
publicvoidtest(){
StringhttpOrgCreateTest=url+"httpOrg/create";
Map<String,String>createMap=newHashMap<String,String>();
createMap.put("authuser","*****");
createMap.put("authpass","*****");
createMap.put("orgkey","****");
createMap.put("orgname","****");
StringhttpOrgCreateTestRtn=httpClientUtil.doPost(httpOrgCreateTest,createMap,charset);
System.out.println("result:"+httpOrgCreateTestRtn);
}
publicstaticvoidmain(String[]args){
TestMainmain=newTestMain();
main.test();
}
}