httpclient对象请求时报错javax.net.ssl.SSLException: hostname in certificate didn‘t match
生活随笔
收集整理的這篇文章主要介紹了
httpclient对象请求时报错javax.net.ssl.SSLException: hostname in certificate didn‘t match
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
學習httpclient對象請求時出現如下報錯:
出現javax.net.ssl.sslexception報錯是因為證書不匹配的主機名的問題。
可以在請求的時候多加上表示修改org.apache.http的主機名驗證的代碼就可以解決
我的原先報錯的代碼如下:
package com.course.httpclient.demo;import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.testng.annotations.Test;import java.io.IOException;public class MyHttpClient {@Testpublic void test1() throws IOException {//用來存放我們的結果String result;HttpGet get = new HttpGet("https://www.baidu.com/");HttpClient client = new DefaultHttpClient();HttpResponse response = client.execute(get);result = EntityUtils.toString(response.getEntity(),"utf-8");System.out.println(result);} }加上修改org.apache.http的主機名驗證解決方法后為:
package com.course.httpclient.demo;import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.AllowAllHostnameVerifier; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.testng.annotations.Test;import java.io.IOException;public class MyHttpClient {@Testpublic void test1() throws IOException {//用來存放我們的結果String result;HttpGet get = new HttpGet("https://www.baidu.com/");HttpClient client = new DefaultHttpClient();//修改org.apache.http的主機名驗證解決問題SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());HttpResponse response = client.execute(get);result = EntityUtils.toString(response.getEntity(),"utf-8");System.out.println(result);} }運行成功:
總結
以上是生活随笔為你收集整理的httpclient对象请求时报错javax.net.ssl.SSLException: hostname in certificate didn‘t match的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: P1571 眼红的Medusa 题解
- 下一篇: 南洋理工大学招募本科生、硕士生和博士生、