导航:首页 > 编程语言 > java实现https

java实现https

发布时间:2023-01-25 05:08:51

java 怎么实现HTTP的POST方式通讯,以及HTTPS方式传递

虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK
库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common
下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。以下是简单的post例子:
String url = "http://www.newsmth.net/bbslogin2.php";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = { new NameValuePair("id", "youUserName"),
new NameValuePair("passwd", "yourPwd") };
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
} else {
System.err.println("Location field value is null.");
}
return;
}

详情见:http://www.ibm.com/developerworks/cn/opensource/os-httpclient/

② 求解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();
}
}

③ java实现https反向代理,提示浏览器版本低

更新即可。java实现https反向代理,提示浏览器版本低更新即可。反向代理方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器。

④ 如何在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 怎么实现HTTP的POST方式通讯,以及HTTPS方式传递

虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK
库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common
下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。以下是简单的post例子:
String url = "http://www.newsmth.net/bbslogin2.php";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = { new NameValuePair("id", "youUserName"),
new NameValuePair("passwd", "yourPwd") };
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
} else {
System.err.println("Location field value is null.");
}
return;
}

⑥ 如何用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请求,我要最新的代码,谢谢

HttpURLConnectionconn=(HttpURLConnection)newURL(url).openConnection();
BufferedReaderbufferReader=newBufferedReader(newInputStreamReader(conn.getInputStream(),"utf-8"));
StringinputLine=null;
while((inputLine=bufferReader.readLine())!=null){
buffer.append(inputLine);
}
bufferReader.close();
conn.disconnect();

System.out.println(inputLine);

⑧ java中怎么将http协议转成https协议

要想实现Http转换成Https,现阶段最简单直接的方法就是使用手动的Http后面加上S即可,不过前提是装好了SSL。如果觉得相当麻烦,我们可以
使用浏览器自带的收藏夹,将常用的Https网站收录进收藏夹,这样下次访问时就可以直接点击,无需手动进行转换了。最好在收藏时进行分类,以免和普通访
问收藏搞混

http和https使用的是完全不同的连接方式,用的端口也不一样,前者是80,后者是443。http的连接很简单,是无状态的。
HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议要比http协议安全。

⑨ 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相关的资料

热点内容
网络流理论算法与应用 浏览:795
java和matlab 浏览:388
钉钉苹果怎么下app软件 浏览:832
php网站验证码不显示 浏览:859
铝膜构造柱要设置加密区吗 浏览:344
考驾照怎么找服务器 浏览:884
阿里云服务器如何更换地区 浏览:972
手机app调音器怎么调古筝 浏览:503
锐起无盘系统在服务器上需要设置什么吗 浏览:19
红旗出租车app怎么应聘 浏览:978
如何编写linux程序 浏览:870
吉利车解压 浏览:248
java输入流字符串 浏览:341
安卓软件没网怎么回事 浏览:785
dvd压缩碟怎么导出电脑 浏览:274
冒险岛什么服务器好玩 浏览:541
如何在服务器上做性能测试 浏览:793
命令序列错 浏览:259
javaif的条件表达式 浏览:576
手机app上传的照片怎么找 浏览:531