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

熱點內容
單片機定時器取余和取整 瀏覽:308
臨沭車輛解壓在哪裡 瀏覽:685
安卓智能手錶如何聽歌 瀏覽:542
win10文件夾取消分組折疊組 瀏覽:664
趨勢指標源碼分析 瀏覽:418
股票價格計算公式源碼 瀏覽:767
程序員解釋方向問題 瀏覽:831
安卓手機關閉屏幕怎麼錄音 瀏覽:232
為什麼老顯示伺服器連接失敗 瀏覽:419
滴答滴app上如何拼車 瀏覽:872
網路加密了怎麼用手機連接 瀏覽:53
香腸樹app等級怎麼看 瀏覽:364
解壓模擬器3d抖音小游戲 瀏覽:319
dlink如何列印伺服器 瀏覽:955
如何啟動後端伺服器 瀏覽:36
電腦安卓軟體界面怎麼默認恢復 瀏覽:266
java程序員接項目 瀏覽:600
炒股指標源碼官網 瀏覽:633
為什麼java安裝不了 瀏覽:559
魅族怎麼更新手機安卓系統 瀏覽:99