java原生发送http请求
根据技术选型总结常见的三种方式发送http请求,本问介绍jdk原生方式,其他两种如下链接
Springboot整合RestTemplate发送http请求
使用JDK原生提供的net包下的HttpURLConnection、URLConnection、Socket三个类都可实现,无需其他jar包
1、HttpURLConnection类实现
HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。
比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面。
请求过程
-
GET:
-
1、创建远程连接
-
2、设置连接方式(get、post、put。。。)
-
3、设置连接超时时间
-
4、设置响应读取时间
-
5、发起请求
-
6、获取请求数据
-
7、关闭连接
-
-
POST:
-
1、创建远程连接
-
2、设置连接方式(get、post、put。。。)
-
3、设置连接超时时间
-
4、设置响应读取时间
-
5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
-
6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)
-
7、设置传入参数的格式:(setRequestProperty)
-
8、设置鉴权信息:Authorization:(setRequestProperty)
-
9、设置参数
-
10、发起请求
-
11、获取请求数据
-
12、关闭连接
代码
-
package com.riemann.springbootdemo.util.common.httpConnectionUtil;
-
-
import org.springframework.lang.Nullable;
-
-
import java.io.*;
-
import java.net.HttpURLConnection;
-
import java.net.MalformedURLException;
-
import java.net.URL;
-
import java.net.URLConnection;
-
-
-
public class HttpURLConnectionUtil {
-
-
/**
-
* Http get请求
-
* @param httpUrl 连接
-
* @return 响应数据
-
*/
-
public static String doGet(String httpUrl){
-
//链接
-
HttpURLConnection connection = null;
-
InputStream is = null;
-
BufferedReader br = null;
-
StringBuffer result = new StringBuffer();
-
try {
-
//创建连接
-
URL url = new URL(httpUrl);
-
connection = (HttpURLConnection) url.openConnection();
-
//设置请求方式
-
connection.setRequestMethod("GET");
-
//设置连接超时时间
-
connection.setReadTimeout(15000);
-
//开始连接
-
connection.connect();
-
//获取响应数据
-
if (connection.getResponseCode() == 200) {
-
//获取返回的数据
-
is = connection.getInputStream();
-
if (null != is) {
-
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
-
String temp = null;
-
while (null != (temp = br.readLine())) {
-
result.append(temp);
-
}
-
}
-
}
-
} catch (IOException e) {
-
e.printStackTrace();
-
} finally {
-
if (null != br) {
-
try {
-
br.close();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
if (null != is) {
-
try {
-
is.close();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
//关闭远程连接
-
connection.disconnect();
-
}
-
return result.toString();
-
}
-
-
/**
-
* Http post请求
-
* @param httpUrl 连接
-
* @param param 参数
-
* @return
-
*/
-
public static String doPost(String httpUrl, { String param)
-
StringBuffer result = new StringBuffer();
-
//连接
-
HttpURLConnection connection = null;
-
OutputStream os = null;
-
InputStream is = null;
-
BufferedReader br = null;
-
try {
-
//创建连接对象
-
URL url = new URL(httpUrl);
-
//创建连接
-
connection = (HttpURLConnection) url.openConnection();
-
//设置请求方法
-
connection.setRequestMethod("POST");
-
//设置连接超时时间
-
connection.setConnectTimeout(15000);
-
//设置读取超时时间
-
connection.setReadTimeout(15000);
-
//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
-
//设置是否可读取
-
connection.setDoOutput(true);
-
connection.setDoInput(true);
-
//设置通用的请求属性
-
connection.setRequestProperty("accept", "*/*");
-
connection.setRequestProperty("connection", "Keep-Alive");
-
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
-
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
-
-
//拼装参数
-
if (null != param && param.equals("")) {
-
//设置参数
-
os = connection.getOutputStream();
-
//拼装参数
-
os.write(param.getBytes("UTF-8"));
-
}
-
//设置权限
-
//设置请求头等
-
//开启连接
-
//connection.connect();
-
//读取响应
-
if (connection.getResponseCode() == 200) {
-
is = connection.getInputStream();
-
if (null != is) {
-
br = new BufferedReader(new InputStreamReader(is, "GBK"));
-
String temp = null;
-
while (null != (temp = br.readLine())) {
-
result.append(temp);
-
result.append("\r\n");
-
}
-
}
-
}
-
-
} catch (MalformedURLException e) {
-
e.printStackTrace();
-
} catch (IOException e) {
-
e.printStackTrace();
-
} finally {
-
//关闭连接
-
if(br!=null){
-
try {
-
br.close();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
if(os!=null){
-
try {
-
os.close();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
if(is!=null){
-
try {
-
is.close();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
//关闭连接
-
connection.disconnect();
-
}
-
return result.toString();
-
}
-
-
public static void main(String[] args) {
-
String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
-
System.out.println(message);
-
}
-
}
2、URLConnection类实现
-
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();
-
-
//设置请求需要返回的数据类型和字符集类型
-
con.setRequestProperty("Content-Type", "application/json;charset=GBK");
-
//允许写出
-
con.setDoOutput(true);
-
//允许读入
-
con.setDoInput(true);
-
//不使用缓存
-
con.setUseCaches(false);
-
//得到响应流
-
InputStream inputStream = con.getInputStream();
-
//将响应流转换成字符串
-
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、Socket类实现
-
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协议
-
*/
-
// socket = new Socket(this.host, this.port);
-
-
/**
-
* https协议
-
*/
-
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协议测试
-
*/
-
//SocketForHttpTest forHttpTest = new SocketForHttpTest("www.百度.com", 80);
-
/**
-
* https协议测试
-
*/
-
SocketForHttpTest forHttpTest = new SocketForHttpTest("www.百度.com", 443);
-
try {
-
forHttpTest.sendGet();
-
// forHttpTest.sendPost();
-
} catch (IOException e) {
-
-
e.printStackTrace();
-
}
-
}
-
-
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhekfcgb
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
怎样阻止微信小程序自动打开
PHP中文网 06-13