導航:首頁 > 編程語言 > 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相關的資料

熱點內容
考駕照怎麼找伺服器 瀏覽:882
阿里雲伺服器如何更換地區 瀏覽:970
手機app調音器怎麼調古箏 瀏覽:501
銳起無盤系統在伺服器上需要設置什麼嗎 瀏覽:17
紅旗計程車app怎麼應聘 瀏覽:978
如何編寫linux程序 瀏覽:870
吉利車解壓 瀏覽:248
java輸入流字元串 瀏覽:341
安卓軟體沒網怎麼回事 瀏覽:785
dvd壓縮碟怎麼導出電腦 瀏覽:274
冒險島什麼伺服器好玩 瀏覽:541
如何在伺服器上做性能測試 瀏覽:793
命令序列錯 瀏覽:259
javaif的條件表達式 瀏覽:576
手機app上傳的照片怎麼找 瀏覽:531
雲伺服器面臨哪些威脅 瀏覽:748
c語言各種編譯特點 瀏覽:177
路由器多種加密方法 瀏覽:604
程序員阻止電腦自動彈出定位 瀏覽:168
如何做伺服器服務商 瀏覽:763