如何在java中发起http和https请求 配置信任

记录下项目中遇到的问题

转自:http://blog.csdn.net/guozili1/article/details/53995121


一般调用外部接口会需要用到httphttps请求。

一.发起http请求

1.写http请求方法

[java]  view plain  copy
  1. //处理http请求  requestUrl为请求地址  requestMethod请求方式,值为"GET"或"POST"  
  2.     public static String httpRequest(String requestUrl,String requestMethod,String outputStr){  
  3.         StringBuffer buffer=null;  
  4.         try{  
  5.         URL url=new URL(requestUrl);  
  6.         HttpURLConnection conn=(HttpURLConnection)url.openConnection();  
  7.         conn.setDoOutput(true);  
  8.         conn.setDoInput(true);  
  9.         conn.setRequestMethod(requestMethod);  
  10.         conn.connect();  
  11.         //往服务器端写内容 也就是发起http请求需要带的参数  
  12.         if(null!=outputStr){  
  13.             OutputStream os=conn.getOutputStream();  
  14.             os.write(outputStr.getBytes("utf-8"));  
  15.             os.close();  
  16.         }  
  17.           
  18.         //读取服务器端返回的内容  
  19.         InputStream is=conn.getInputStream();  
  20.         InputStreamReader isr=new InputStreamReader(is,"utf-8");  
  21.         BufferedReader br=new BufferedReader(isr);  
  22.         buffer=new StringBuffer();  
  23.         String line=null;  
  24.         while((line=br.readLine())!=null){  
  25.             buffer.append(line);  
  26.         }  
  27.         }catch(Exception e){  
  28.             e.printStackTrace();  
  29.         }  
  30.         return buffer.toString();  
  31.     }  
2.测试。

[java]  view plain  copy
  1. public static void main(String[] args){  
  2.         String s=httpRequest("http://www.qq.com","GET",null);  
  3.         System.out.println(s);  
  4.     }  

输出结果为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  copy
  1. import java.security.cert.CertificateException;  
  2. import java.security.cert.X509Certificate;  
  3. import javax.net.ssl.X509TrustManager;  
  4.   
  5. public class MyX509TrustManager implements X509TrustManager {  
  6.   
  7.     @Override  
  8.     public void checkClientTrusted(X509Certificate[] chain, String authType)  
  9.             throws CertificateException {  
  10.         // TODO Auto-generated method stub  
  11.   
  12.     }  
  13.   
  14.     @Override  
  15.     public void checkServerTrusted(X509Certificate[] chain, String authType)  
  16.             throws CertificateException {  
  17.         // TODO Auto-generated method stub  
  18.   
  19.     }  
  20.   
  21.     @Override  
  22.     public X509Certificate[] getAcceptedIssuers() {  
  23.         // TODO Auto-generated method stub  
  24.         return null;  
  25.     }  
  26.   
  27. }  

注:1)需要的包都是java自带的,所以不用引入额外的包。

2.)可以看到里面的方法都是空的,当方法为空是默认为所有的链接都为安全,也就是所有的链接都能够访问到。当然这样有一定的安全风险,可以根据实际需要写入内容。

2.编写https请求方法。

[java]  view plain  copy
  1. /* 
  2.  * 处理https GET/POST请求 
  3.  * 请求地址、请求方法、参数 
  4.  * */  
  5. public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){  
  6.     StringBuffer buffer=null;  
  7.     try{  
  8.     //创建SSLContext  
  9.     SSLContext sslContext=SSLContext.getInstance("SSL");  
  10.     TrustManager[] tm={new MyX509TrustManager()};  
  11.     //初始化  
  12.     sslContext.init(null, tm, new java.security.SecureRandom());;  
  13.     //获取SSLSocketFactory对象  
  14.     SSLSocketFactory ssf=sslContext.getSocketFactory();  
  15.     URL url=new URL(requestUrl);  
  16.     HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();  
  17.     conn.setDoOutput(true);  
  18.     conn.setDoInput(true);  
  19.     conn.setUseCaches(false);  
  20.     conn.setRequestMethod(requestMethod);  
  21.     //设置当前实例使用的SSLSoctetFactory  
  22.     conn.setSSLSocketFactory(ssf);  
  23.     conn.connect();  
  24.     //往服务器端写内容  
  25.     if(null!=outputStr){  
  26.         OutputStream os=conn.getOutputStream();  
  27.         os.write(outputStr.getBytes("utf-8"));  
  28.         os.close();  
  29.     }  
  30.       
  31.     //读取服务器端返回的内容  
  32.     InputStream is=conn.getInputStream();  
  33.     InputStreamReader isr=new InputStreamReader(is,"utf-8");  
  34.     BufferedReader br=new BufferedReader(isr);  
  35.     buffer=new StringBuffer();  
  36.     String line=null;  
  37.     while((line=br.readLine())!=null){  
  38.         buffer.append(line);  
  39.     }  
  40.     }catch(Exception e){  
  41.         e.printStackTrace();  
  42.     }  
  43.     return buffer.toString();  
  44. }  
可见和http访问的方法类似,只是多了SSL的相关处理。

3.测试。先用http请求的方法访问,再用https的请求方法访问,进行对比。

http访问:

[java]  view plain  copy
  1. public static void main(String[] args){  
  2.         String s=httpRequest("https://kyfw.12306.cn/","GET",null);  
  3.         System.out.println(s);  
  4.     }  
结果为:

https访问:

[java]  view plain  copy
  1. public static void main(String[] args){  
  2.     String s=httpsRequest("https://kyfw.12306.cn/","GET",null);  
  3.     System.out.println(s);  
  4. }  
结果为:

可见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  copy
  1. public static void main(String[] args){  
  2.         String s=httpRequest("https://kyfw.12306.cn/","GET",null);  
  3.         System.out.println(s);  
  4.     }  

结果:



现在就可以用http的方法请求https了。

注:有时候这一步还是会出错,那可能是jre的版本不对,我们右键run as——run configurations,选择证书所在的jre之后再运行。



6.最后证书的查看和删除命令为:






  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java ,可以使用 java.net 包HttpURLConnection 类来实现通过代理服务器发起 HTTP 请求。具体实现方法可以参考以下示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; public class HttpRequestWithProxy { public static void main(String[] args) throws IOException { String url = "http://example.com"; String proxyHost = "proxy.example.com"; int proxyPort = 8080; String proxyUser = "username"; String proxyPassword = "password"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); URL urlObj = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(proxy); String auth = proxyUser + ":" + proxyPassword; String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes()); connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedAuth); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } } ``` 在代码,我们使用了代理服务器 "proxy.example.com",端口为 8080,并提供了用户名和密码进行身份验证。我们通过 new Proxy() 创建了代理对象,并在打开 URL 连接时使用了这个代理对象。我们还在请求添加了一个 "Proxy-Authorization" 字段,来提供代理服务器的身份验证信息。 当然,具体的代理服务器设置可能需要根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值