当前位置:首页 » 编程语言 » javahttps

javahttps

发布时间: 2022-09-28 13:10:47

Ⅰ 用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();
}
}
热点内容
外壳加密狗 发布:2024-12-26 08:57:59 浏览:843
笔记本电脑密码怎么破解 发布:2024-12-26 08:57:20 浏览:70
360云盘分享取消密码是多少 发布:2024-12-26 08:55:37 浏览:820
脚本啥格式 发布:2024-12-26 08:55:00 浏览:128
学C语言书 发布:2024-12-26 08:46:46 浏览:84
win7共享文件访问权限 发布:2024-12-26 08:33:22 浏览:147
安卓如何下载play商店app 发布:2024-12-26 08:32:31 浏览:498
我的世界网易服务器卡崩进不去 发布:2024-12-26 08:20:48 浏览:738
sqlserver导出xml 发布:2024-12-26 08:06:26 浏览:289
wifi无访问权限 发布:2024-12-26 08:05:33 浏览:674