JAVA發(fā)送HTTP請求的四種方式總結(jié)
源代碼:http://github.com/lovewenyo/HttpDemo
1. HttpURLConnection
使用JDK原生提供的net,無需其他jar包;
HttpURLConnection是URLConnection的子類,提供更多的方法,使用更方便。
package httpURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionHelper {
public static String sendRequest(String urlParam,String requestType) {
HttpURLConnection con = null;
BufferedReader buffer = null;
StringBuffer resultBuffer = null;
try {
URL url = new URL(urlParam);
//得到連接對(duì)象
con = (HttpURLConnection) url.openConnection();
//設(shè)置請求類型
con.setRequestMethod(requestType);
//設(shè)置請求需要返回的數(shù)據(jù)類型和字符集類型
con.setRequestProperty("Content-Type", "application/json;charset=GBK");
//允許寫出
con.setDoOutput(true);
//允許讀入
con.setDoInput(true);
//不使用緩存
con.setUseCaches(false);
//得到響應(yīng)碼
int responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
//得到響應(yīng)流
InputStream inputStream = con.getInputStream();
//將響應(yīng)流轉(zhuǎn)換成字符串
resultBuffer = new StringBuffer();
String line;
buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
while ((line = buffer.readLine()) != null) {
resultBuffer.append(line);
}
return resultBuffer.toString();
}
}catch(Exception e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
System.out.println(sendRequest(url,"POST"));
}
}
2. URLConnection
使用JDK原生提供的net,無需其他jar包;
建議使用HttpURLConnection
package uRLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class URLConnectionHelper {
public static String sendRequest(String urlParam) {
URLConnection con = null;
BufferedReader buffer = null;
StringBuffer resultBuffer = null;
try {
URL url = new URL(urlParam);
con = url.openConnection();
//設(shè)置請求需要返回的數(shù)據(jù)類型和字符集類型
con.setRequestProperty("Content-Type", "application/json;charset=GBK");
//允許寫出
con.setDoOutput(true);
//允許讀入
con.setDoInput(true);
//不使用緩存
con.setUseCaches(false);
//得到響應(yīng)流
InputStream inputStream = con.getInputStream();
//將響應(yīng)流轉(zhuǎn)換成字符串
resultBuffer = new StringBuffer();
String line;
buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
while ((line = buffer.readLine()) != null) {
resultBuffer.append(line);
}
return resultBuffer.toString();
}catch(Exception e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
System.out.println(sendRequest(url));
}
}
3. HttpClient
使用方便,我個(gè)人偏愛這種方式,但依賴于第三方j(luò)ar包,相關(guān)maven依賴如下:
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient --> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency
package httpClient;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpClientHelper {
public static String sendPost(String urlParam) throws HttpException, IOException {
// 創(chuàng)建httpClient實(shí)例對(duì)象
HttpClient httpClient = new HttpClient();
// 設(shè)置httpClient連接主機(jī)服務(wù)器超時(shí)時(shí)間:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 創(chuàng)建post請求方法實(shí)例對(duì)象
PostMethod postMethod = new PostMethod(urlParam);
// 設(shè)置post請求超時(shí)時(shí)間
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
postMethod.addRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
return result;
}
public static String sendGet(String urlParam) throws HttpException, IOException {
// 創(chuàng)建httpClient實(shí)例對(duì)象
HttpClient httpClient = new HttpClient();
// 設(shè)置httpClient連接主機(jī)服務(wù)器超時(shí)時(shí)間:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 創(chuàng)建GET請求方法實(shí)例對(duì)象
GetMethod getMethod = new GetMethod(urlParam);
// 設(shè)置post請求超時(shí)時(shí)間
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
getMethod.addRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(getMethod);
String result = getMethod.getResponseBodyAsString();
getMethod.releaseConnection();
return result;
}
public static void main(String[] args) throws HttpException, IOException {
String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
System.out.println(sendPost(url));
System.out.println(sendGet(url));
}
}
4. Socket
使用JDK原生提供的net,無需其他jar包;
使用起來有點(diǎn)麻煩。
package socket;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URLEncoder;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class SocketForHttpTest {
private int port;
private String host;
private Socket socket;
private BufferedReader bufferedReader;
private BufferedWriter bufferedWriter;
public SocketForHttpTest(String host,int port) throws Exception{
this.host = host;
this.port = port;
/**
* http協(xié)議
*/
// socket = new Socket(this.host, this.port);
/**
* https協(xié)議
*/
socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(this.host, this.port);
}
public void sendGet() throws IOException{
//String requestUrlPath = "/z69183787/article/details/17580325";
String requestUrlPath = "/";
OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
bufferedWriter = new BufferedWriter(streamWriter);
bufferedWriter.write("GET " + requestUrlPath + " HTTP/1.1\r\n");
bufferedWriter.write("Host: " + this.host + "\r\n");
bufferedWriter.write("\r\n");
bufferedWriter.flush();
BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
String line = null;
while((line = bufferedReader.readLine())!= null){
System.out.println(line);
}
bufferedReader.close();
bufferedWriter.close();
socket.close();
}
public void sendPost() throws IOException{
String path = "/";
String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode("張三", "utf-8") + "&" +
URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("32", "utf-8");
// String data = "name=zhigang_jia";
System.out.println(">>>>>>>>>>>>>>>>>>>>>"+data);
OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
bufferedWriter = new BufferedWriter(streamWriter);
bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");
bufferedWriter.write("Host: " + this.host + "\r\n");
bufferedWriter.write("Content-Length: " + data.length() + "\r\n");
bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");
bufferedWriter.write("\r\n");
bufferedWriter.write(data);
bufferedWriter.write("\r\n");
bufferedWriter.flush();
BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
String line = null;
while((line = bufferedReader.readLine())!= null)
{
System.out.println(line);
}
bufferedReader.close();
bufferedWriter.close();
socket.close();
}
public static void main(String[] args) throws Exception {
/**
* http協(xié)議測試
*/
//SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 80);
/**
* https協(xié)議測試
*/
SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 443);
try {
forHttpTest.sendGet();
// forHttpTest.sendPost();
} catch (IOException e) {
e.printStackTrace();
}
}
}
總結(jié)
到此這篇關(guān)于JAVA發(fā)送HTTP請求的文章就介紹到這了,更多相關(guān)JAVA發(fā)送HTTP請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Eclipse2020安裝了最新版本的JDK卻無法打開的問題
這篇文章主要介紹了Eclipse2020安裝了最新版本的JDK卻無法打開,提示版本太老的完美解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
Java線程的創(chuàng)建介紹及實(shí)現(xiàn)方式示例
這篇文章主要為大家介紹了Java線程的創(chuàng)建介紹及實(shí)現(xiàn)方式示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
SpringSecurity?用戶帳號(hào)已被鎖定的問題及解決方法
這篇文章主要介紹了SpringSecurity?用戶帳號(hào)已被鎖定,本文給大家分享問題原因及解決方式,需要的朋友可以參考下2023-12-12
Java語法基礎(chǔ)之選擇結(jié)構(gòu)的if語句、switch語句詳解
這篇文章主要為大詳細(xì)介紹了Java語法基礎(chǔ)之選擇結(jié)構(gòu)的if語句、switch語句,感興趣的小伙伴們可以參考一下2016-09-09
使用RestTemplate調(diào)用RESTful?API的代碼示例
在開發(fā)?Web?應(yīng)用程序時(shí),調(diào)用?RESTful?API?是一個(gè)常見的任務(wù),本文將介紹如何使用?RestTemplate?調(diào)用?RESTful?API,并提供示例代碼,感興趣的同學(xué)可以跟著小編一起來看看2023-06-06
java如何實(shí)現(xiàn)項(xiàng)目啟動(dòng)時(shí)執(zhí)行指定方法
這篇文章主要為大家詳細(xì)介紹了java項(xiàng)目如何啟動(dòng)時(shí)執(zhí)行指定方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
SpringBoot+Vue3實(shí)現(xiàn)七牛云大視頻上傳
現(xiàn)代Web應(yīng)用中文件上傳很重要,本文用Vue.js和Spring Boot實(shí)現(xiàn)視頻上傳功能,同時(shí)使用七牛云作為存儲(chǔ)服務(wù),文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-07-07
MyBatisPlus唯一索引批量新增或修改的實(shí)現(xiàn)方法
本文主要介紹了MyBatisPlus唯一索引批量新增或修改的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03

