導航:首頁 > 編程語言 > java訪問http

java訪問http

發布時間:2022-08-11 13:01:20

1. 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;
}

2. java如何調用對方http介面 新手虛心求教

importjava.io.BufferedReader;
importjava.io.DataOutputStream;
importjava.io.InputStreamReader;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.net.URLEncoder;

publicclassDemoTest1{

publicstaticfinalStringGET_URL="http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
//publicstaticfinalStringPOST_URL="http://112.4.27.9/mall-back/if_user/store_list";
//妙兜測試介面
publicstaticfinalStringPOST_URL="http://121.40.204.191:8180/mdserver/service/installLock";

/**
*介面調用GET
*/
(){
try{
URLurl=newURL(GET_URL);//把字元串轉換為URL請求地址
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//打開連接
connection.connect();//連接會話
//獲取輸入流
BufferedReaderbr=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){//循環讀取流
sb.append(line);
}
br.close();//關閉流
connection.disconnect();//斷開連接
System.out.println(sb.toString());
}catch(Exceptione){
e.printStackTrace();
System.out.println("失敗!");
}
}

/**
*介面調用POST
*/
(){
try{
URLurl=newURL(POST_URL);

//將url以open方法返回的urlConnection連接強轉為HttpURLConnection連接(標識一個url所引用的遠程對象連接)
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//此時cnnection只是為一個連接對象,待連接中

//設置連接輸出流為true,默認false(post請求是以流的方式隱式的傳遞參數)
connection.setDoOutput(true);

//設置連接輸入流為true
connection.setDoInput(true);

//設置請求方式為post
connection.setRequestMethod("POST");

//post請求緩存設為false
connection.setUseCaches(false);

//設置該HttpURLConnection實例是否自動執行重定向
connection.setInstanceFollowRedirects(true);

//設置請求頭裡面的各個屬性(以下為設置內容的類型,設置為經過urlEncoded編碼過的from參數)
//application/x-javascripttext/xml->xml數據application/x-javascript->json對象application/x-www-form-urlencoded->表單數據
//;charset=utf-8必須要,不然妙兜那邊會出現亂碼【★★★★★】
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

//建立連接(請求未開始,直到connection.getInputStream()方法調用時才發起,以上各個參數設置需在此方法之前進行)
connection.connect();

//創建輸入輸出流,用於往連接裡面輸出攜帶的參數,(輸出內容為?後面的內容)
DataOutputStreamdataout=newDataOutputStream(connection.getOutputStream());

Stringapp_key="app_key="+URLEncoder.encode("","utf-8");//已修改【改為錯誤數據,以免信息泄露】
Stringagt_num="&agt_num="+URLEncoder.encode("10111","utf-8");//已修改【改為錯誤數據,以免信息泄露】
Stringpid="&pid="+URLEncoder.encode("BLZXA150401111","utf-8");//已修改【改為錯誤數據,以免信息泄露】
Stringdepartid="&departid="+URLEncoder.encode("10007111","utf-8");//已修改【改為錯誤數據,以免信息泄露】
Stringinstall_lock_name="&install_lock_name="+URLEncoder.encode("南天大門","utf-8");
Stringinstall_address="&install_address="+URLEncoder.encode("北京育新","utf-8");
Stringinstall_gps="&install_gps="+URLEncoder.encode("116.350888,40.011001","utf-8");
Stringinstall_work="&install_work="+URLEncoder.encode("小李","utf-8");
Stringinstall_telete="&install_telete="+URLEncoder.encode("13000000000","utf-8");
Stringintall_comm="&intall_comm="+URLEncoder.encode("一切正常","utf-8");

//格式parm=aaa=111&bbb=222&ccc=333&ddd=444
Stringparm=app_key+agt_num+pid+departid+install_lock_name+install_address+install_gps+install_work+install_telete+intall_comm;

//將參數輸出到連接
dataout.writeBytes(parm);

//輸出完成後刷新並關閉流
dataout.flush();
dataout.close();//重要且易忽略步驟(關閉流,切記!)

//System.out.println(connection.getResponseCode());

//連接發起請求,處理伺服器響應(從連接獲取到輸入流並包裝為bufferedReader)
BufferedReaderbf=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();//用來存儲響應數據

//循環讀取流,若不到結尾處
while((line=bf.readLine())!=null){
//sb.append(bf.readLine());
sb.append(line).append(System.getProperty("line.separator"));
}
bf.close();//重要且易忽略步驟(關閉流,切記!)
connection.disconnect();//銷毀連接
System.out.println(sb.toString());

}catch(Exceptione){
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args){
//httpURLConectionGET();
httpURLConnectionPOST();
}
}

3. java 如何實現 http協議傳輸

Java 6 提供了一個輕量級的純 Java Http 伺服器的實現。下面是一個簡單的例子:

public static void main(String[] args) throws Exception{
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
InetSocketAddress addr = new InetSocketAddress(7778);
HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/myapp/", new MyHttpHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}

static class MyHttpHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
String response = "Hello world!";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
}
}

然後,在瀏覽器中訪問 http://localhost:7778/myapp/

4. 如何在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之後再運行。

5. java雙網卡怎麼做http訪問

用雙網卡同時訪問內外網暫時沒有很完美的解決辦法,因為存在路由沖突,畢竟有兩個網關地址,現在可以試試下面的辦法:
先來解決雙網卡沖突的問題。可以通過改變路由地址表搞定。以你的單位用機為例,機器有兩塊網卡,接到兩台路由器上:
內部網地址設置為192.168.1.110,子網掩碼:255.255.255.0,網關:192.168.1.1
辦公網地址:10.94.12.123,子網掩碼:255.255.255.0,網關:10.94.12.254
如果按正常的設置方法設置每塊網卡的IP地址和網關,再cmd下使用route print查看時會看到以0.0.0.0 0.0.0.0 開頭的兩個東西,即指向0.0.0.0的有兩個網關,這樣就會出現路由沖突,兩個網路的訪問存在困難。要實現同時訪問兩個網路就要用到route命令

6. java如何使用http方式調用第三方介面最好有代碼~謝謝

星號是IP地址和埠號
public class HttpUtil {
private final static Log log = LogFactory.getLog(HttpUtil.class);
public static String doHttpOutput(String outputStr,String method) throws Exception {
Map map = new HashMap();
String URL = "http://****/interface/http.php" ;
String result = "";
InputStream is = null;
int len = 0;
int tmp = 0;

OutputStream output = null;
BufferedOutputStream objOutput = null;
String charSet = "gbk";
System.out.println("URL of fpcy request");
System.out.println("=============================");
System.out.println(URL);
System.out.println("=============================");
HttpURLConnection con = getConnection(URL);
try {
output = con.getOutputStream();
objOutput = new BufferedOutputStream(output);
objOutput.write(outputStr.getBytes(charSet));
objOutput.flush();
output.close();
objOutput.close();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
is = con.getInputStream();
int dataLen = is.available();
int retry = 5;
while (dataLen == 0 && retry > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
dataLen = is.available();
retry--;
log.info("未獲取到任何數據,嘗試重試,當前剩餘次數" + retry);
}
log.info("獲取到報文單位數據長度:" + dataLen);
byte[] bytes = new byte[dataLen];
while ((tmp = is.read()) != -1) {
bytes[len++] = (byte) tmp;
if (len == dataLen) {
dataLen = bytes.length + dataLen;
byte[] newbytes = new byte[dataLen];
for (int i = 0; i < bytes.length; i++) {
newbytes[i] = bytes[i];
}
bytes = newbytes;
}
}
result = new String(bytes, 0, len, charSet);
} else {
String responseMsg = "調用介面失敗,返回錯誤信息:" + con.getResponseMessage() + "(" + responseCode + ")";
System.out.println(responseMsg);
throw new Exception(responseMsg);
}
} catch (IOException e2) {
log.error(e2.getMessage(), e2);
throw new Exception("介面連接超時!,請檢查網路");
}
con.disconnect();
System.out.println("=============================");
System.out.println("Contents of fpcy response");
System.out.println("=============================");
System.out.println(result);
Thread.sleep(1000);
return result;
}
private static HttpURLConnection getConnection(String URL) throws Exception {
Map map = new HashMap();
int rTimeout = 15000;
int cTimeout = 15000;
String method = "";
method = "POST";
boolean useCache = false;
useCache = false;
HttpURLConnection con = null;
try {
con = (HttpURLConnection) new URL(URL).openConnection();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("URL不合法!");
}
try {
con.setRequestMethod(method);
} catch (ProtocolException e) {
log.error(e.getMessage(), e);
throw new Exception("通信協議不合法!");
}
con.setConnectTimeout(cTimeout);
con.setReadTimeout(rTimeout);
con.setUseCaches(useCache);
con.setDoInput(true);
con.setDoOutput(true);
log.info("當前連接信息: URL:" + URL + "," + "Method:" + method
+ ",ReadTimeout:" + rTimeout + ",ConnectTimeOut:" + cTimeout
+ ",UseCaches:" + useCache);
return con;
}

public static void main(String[] args) throws Exception {
String xml="<?xml version=\"1.0\" encoding=\"GBK\" ?><document><txcode>101</txcode><netnumber>100001</netnumber>.........</document>";

response=HttpUtil.doHttpOutput(xml, "post");
JSONObject json= JSONObject.parseObject(response);
String retcode=json.getString("retcode");
調用這個類就能獲得返回的參數。。over.

}

}
}

7. java 接受http請求

使用servlet


public class Test extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public Test() {

super();

// TODO Auto-generated constructor stub

}


/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收get請求

// 這里寫你接收request請求後要處理的操作

}


/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收post請求

// 這里寫你接收request請求後要處理的操作

}


}


8. java 怎麼接收http請求

用servlet接收。
具體步驟是寫一個類繼承HttpServlet,如果是接收get請求就重寫doGet(HttpServletRequest,HttpServletResponse),接收post就重寫doPost(HttpServletRequest,HttpServletResponse),共同處理post和get就重寫service(HttpServletRequest,HttpServletResponse)
其次在web.xml定義servlet標簽,以及你這個servlet要處理的請求mapping
最後把項目部署在tomcat之類的web容器中即可。
如果使用框架的話就另當別論了,比如spring 的DispatcherServlet。當然你也可以自己寫servlet。

9. java 怎麼調用http介面

方法:只要New一個Map,然後把要傳遞的參數以鍵值對的形式存入Map即可。privatevoidExample(){Stringurl=地址;Mapparam=newHashMap();p.put("ParamName","ParamValue");Stringhtml=this.visitURL(url,param);}

10. java如何調用對方http介面

你是指發送http請求嗎,可以使用Apache 的 HttpClient

//構建HttpClient實例
CloseableHttpClienthttpclient=HttpClients.createDefault();//設置請求超時時間
RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();//指定POST請求
HttpPosthttppost=newHttpPost(url);
httppost.setConfig(requestConfig);//包裝請求體
List<NameValuePair>params=newArrayList<NameValuePair>();params.addAll(content);
HttpEntityrequest=newUrlEncodedFormEntity(params,"UTF-8");//發送請求
httppost.setEntity(request);
=httpclient.execute(httppost);//讀取響應
HttpEntityentity=httpResponse.getEntity();Stringresult=null;if(entity!=null){
result=EntityUtils.toString(entity,"UTF-8");
}
閱讀全文

與java訪問http相關的資料

熱點內容
php個性qq源碼 瀏覽:821
初學c語言顯示源未編譯 瀏覽:245
資產概況源碼 瀏覽:472
dos命令建文件夾命令 瀏覽:379
解壓的密碼htm被屏蔽 瀏覽:502
冬天太冷冰箱壓縮機不啟動怎麼辦 瀏覽:83
手機打開vcf需要什麼編譯器 瀏覽:910
加密磁碟後開機很慢 瀏覽:271
長沙智能雲控系統源碼 瀏覽:258
阿里雲伺服器如何設置操作系統 瀏覽:999
超級命令的英文 瀏覽:784
做賬為什麼要用加密狗 瀏覽:586
考研群體怎麼解壓 瀏覽:159
linux修改命令提示符 瀏覽:226
圓圈裡面k圖標是什麼app 瀏覽:63
pdf加空白頁 瀏覽:948
linux伺服器如何看網卡狀態 瀏覽:318
解壓新奇特視頻 瀏覽:707
圖書信息管理系統java 瀏覽:554
各種直線命令詳解 瀏覽:864