• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

java原生发送http请求

武飞扬头像
程序三两行
帮助3

根据技术选型总结常见的三种方式发送http请求,本问介绍jdk原生方式,其他两种如下链接

httpclient和okhttp

Springboot整合RestTemplate发送http请求

使用JDK原生提供的net包下的HttpURLConnection、URLConnection、Socket三个类都可实现,无需其他jar包

1、HttpURLConnection类实现

HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。

比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面。

请求过程

  1.  
    GET:
  2.  
    1、创建远程连接
  3.  
    2、设置连接方式(get、post、put。。。)
  4.  
    3、设置连接超时时间
  5.  
    4、设置响应读取时间
  6.  
    5、发起请求
  7.  
    6、获取请求数据
  8.  
    7、关闭连接
  9.  
     
  10.  
    POST:
  11.  
    1、创建远程连接
  12.  
    2、设置连接方式(get、post、put。。。)
  13.  
    3、设置连接超时时间
  14.  
    4、设置响应读取时间
  15.  
    5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
  16.  
    6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)
  17.  
    7、设置传入参数的格式:(setRequestProperty)
  18.  
    8、设置鉴权信息:Authorization:(setRequestProperty)
  19.  
    9、设置参数
  20.  
    10、发起请求
  21.  
    11、获取请求数据
  22.  
    12、关闭连接

代码

  1.  
    package com.riemann.springbootdemo.util.common.httpConnectionUtil;
  2.  
     
  3.  
    import org.springframework.lang.Nullable;
  4.  
     
  5.  
    import java.io.*;
  6.  
    import java.net.HttpURLConnection;
  7.  
    import java.net.MalformedURLException;
  8.  
    import java.net.URL;
  9.  
    import java.net.URLConnection;
  10.  
     
  11.  
     
  12.  
    public class HttpURLConnectionUtil {
  13.  
     
  14.  
    /**
  15.  
    * Http get请求
  16.  
    * @param httpUrl 连接
  17.  
    * @return 响应数据
  18.  
    */
  19.  
    public static String doGet(String httpUrl){
  20.  
    //链接
  21.  
    HttpURLConnection connection = null;
  22.  
    InputStream is = null;
  23.  
    BufferedReader br = null;
  24.  
    StringBuffer result = new StringBuffer();
  25.  
    try {
  26.  
    //创建连接
  27.  
    URL url = new URL(httpUrl);
  28.  
    connection = (HttpURLConnection) url.openConnection();
  29.  
    //设置请求方式
  30.  
    connection.setRequestMethod("GET");
  31.  
    //设置连接超时时间
  32.  
    connection.setReadTimeout(15000);
  33.  
    //开始连接
  34.  
    connection.connect();
  35.  
    //获取响应数据
  36.  
    if (connection.getResponseCode() == 200) {
  37.  
    //获取返回的数据
  38.  
    is = connection.getInputStream();
  39.  
    if (null != is) {
  40.  
    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  41.  
    String temp = null;
  42.  
    while (null != (temp = br.readLine())) {
  43.  
    result.append(temp);
  44.  
    }
  45.  
    }
  46.  
    }
  47.  
    } catch (IOException e) {
  48.  
    e.printStackTrace();
  49.  
    } finally {
  50.  
    if (null != br) {
  51.  
    try {
  52.  
    br.close();
  53.  
    } catch (IOException e) {
  54.  
    e.printStackTrace();
  55.  
    }
  56.  
    }
  57.  
    if (null != is) {
  58.  
    try {
  59.  
    is.close();
  60.  
    } catch (IOException e) {
  61.  
    e.printStackTrace();
  62.  
    }
  63.  
    }
  64.  
    //关闭远程连接
  65.  
    connection.disconnect();
  66.  
    }
  67.  
    return result.toString();
  68.  
    }
  69.  
     
  70.  
    /**
  71.  
    * Http post请求
  72.  
    * @param httpUrl 连接
  73.  
    * @param param 参数
  74.  
    * @return
  75.  
    */
  76.  
    public static String doPost(String httpUrl, @Nullable String param) {
  77.  
    StringBuffer result = new StringBuffer();
  78.  
    //连接
  79.  
    HttpURLConnection connection = null;
  80.  
    OutputStream os = null;
  81.  
    InputStream is = null;
  82.  
    BufferedReader br = null;
  83.  
    try {
  84.  
    //创建连接对象
  85.  
    URL url = new URL(httpUrl);
  86.  
    //创建连接
  87.  
    connection = (HttpURLConnection) url.openConnection();
  88.  
    //设置请求方法
  89.  
    connection.setRequestMethod("POST");
  90.  
    //设置连接超时时间
  91.  
    connection.setConnectTimeout(15000);
  92.  
    //设置读取超时时间
  93.  
    connection.setReadTimeout(15000);
  94.  
    //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
  95.  
    //设置是否可读取
  96.  
    connection.setDoOutput(true);
  97.  
    connection.setDoInput(true);
  98.  
    //设置通用的请求属性
  99.  
    connection.setRequestProperty("accept", "*/*");
  100.  
    connection.setRequestProperty("connection", "Keep-Alive");
  101.  
    connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  102.  
    connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
  103.  
     
  104.  
    //拼装参数
  105.  
    if (null != param && param.equals("")) {
  106.  
    //设置参数
  107.  
    os = connection.getOutputStream();
  108.  
    //拼装参数
  109.  
    os.write(param.getBytes("UTF-8"));
  110.  
    }
  111.  
    //设置权限
  112.  
    //设置请求头等
  113.  
    //开启连接
  114.  
    //connection.connect();
  115.  
    //读取响应
  116.  
    if (connection.getResponseCode() == 200) {
  117.  
    is = connection.getInputStream();
  118.  
    if (null != is) {
  119.  
    br = new BufferedReader(new InputStreamReader(is, "GBK"));
  120.  
    String temp = null;
  121.  
    while (null != (temp = br.readLine())) {
  122.  
    result.append(temp);
  123.  
    result.append("\r\n");
  124.  
    }
  125.  
    }
  126.  
    }
  127.  
     
  128.  
    } catch (MalformedURLException e) {
  129.  
    e.printStackTrace();
  130.  
    } catch (IOException e) {
  131.  
    e.printStackTrace();
  132.  
    } finally {
  133.  
    //关闭连接
  134.  
    if(br!=null){
  135.  
    try {
  136.  
    br.close();
  137.  
    } catch (IOException e) {
  138.  
    e.printStackTrace();
  139.  
    }
  140.  
    }
  141.  
    if(os!=null){
  142.  
    try {
  143.  
    os.close();
  144.  
    } catch (IOException e) {
  145.  
    e.printStackTrace();
  146.  
    }
  147.  
    }
  148.  
    if(is!=null){
  149.  
    try {
  150.  
    is.close();
  151.  
    } catch (IOException e) {
  152.  
    e.printStackTrace();
  153.  
    }
  154.  
    }
  155.  
    //关闭连接
  156.  
    connection.disconnect();
  157.  
    }
  158.  
    return result.toString();
  159.  
    }
  160.  
     
  161.  
    public static void main(String[] args) {
  162.  
    String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
  163.  
    System.out.println(message);
  164.  
    }
  165.  
    }

2、URLConnection类实现

  1.  
    package uRLConnection;
  2.  
     
  3.  
    import java.io.BufferedReader;
  4.  
    import java.io.InputStream;
  5.  
    import java.io.InputStreamReader;
  6.  
    import java.net.HttpURLConnection;
  7.  
    import java.net.URL;
  8.  
    import java.net.URLConnection;
  9.  
     
  10.  
    public class URLConnectionHelper {
  11.  
     
  12.  
    public static String sendRequest(String urlParam) {
  13.  
     
  14.  
    URLConnection con = null;
  15.  
     
  16.  
    BufferedReader buffer = null;
  17.  
    StringBuffer resultBuffer = null;
  18.  
     
  19.  
    try {
  20.  
    URL url = new URL(urlParam);
  21.  
    con = url.openConnection();
  22.  
     
  23.  
    //设置请求需要返回的数据类型和字符集类型
  24.  
    con.setRequestProperty("Content-Type", "application/json;charset=GBK");
  25.  
    //允许写出
  26.  
    con.setDoOutput(true);
  27.  
    //允许读入
  28.  
    con.setDoInput(true);
  29.  
    //不使用缓存
  30.  
    con.setUseCaches(false);
  31.  
    //得到响应流
  32.  
    InputStream inputStream = con.getInputStream();
  33.  
    //将响应流转换成字符串
  34.  
    resultBuffer = new StringBuffer();
  35.  
    String line;
  36.  
    buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
  37.  
    while ((line = buffer.readLine()) != null) {
  38.  
    resultBuffer.append(line);
  39.  
    }
  40.  
    return resultBuffer.toString();
  41.  
     
  42.  
    }catch(Exception e) {
  43.  
    e.printStackTrace();
  44.  
    }
  45.  
     
  46.  
    return "";
  47.  
    }
  48.  
    public static void main(String[] args) {
  49.  
    String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
  50.  
    System.out.println(sendRequest(url));
  51.  
    }
  52.  
    }

3、Socket类实现

  1.  
    package socket;
  2.  
    import java.io.BufferedInputStream;
  3.  
    import java.io.BufferedReader;
  4.  
    import java.io.BufferedWriter;
  5.  
    import java.io.IOException;
  6.  
    import java.io.InputStreamReader;
  7.  
    import java.io.OutputStreamWriter;
  8.  
    import java.net.Socket;
  9.  
    import java.net.URLEncoder;
  10.  
     
  11.  
    import javax.net.ssl.SSLSocket;
  12.  
    import javax.net.ssl.SSLSocketFactory;
  13.  
     
  14.  
    public class SocketForHttpTest {
  15.  
     
  16.  
    private int port;
  17.  
    private String host;
  18.  
    private Socket socket;
  19.  
    private BufferedReader bufferedReader;
  20.  
    private BufferedWriter bufferedWriter;
  21.  
     
  22.  
    public SocketForHttpTest(String host,int port) throws Exception{
  23.  
     
  24.  
    this.host = host;
  25.  
    this.port = port;
  26.  
     
  27.  
    /**
  28.  
    * http协议
  29.  
    */
  30.  
    // socket = new Socket(this.host, this.port);
  31.  
     
  32.  
    /**
  33.  
    * https协议
  34.  
    */
  35.  
    socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(this.host, this.port);
  36.  
     
  37.  
     
  38.  
    }
  39.  
     
  40.  
    public void sendGet() throws IOException{
  41.  
    //String requestUrlPath = "/z69183787/article/details/17580325";
  42.  
    String requestUrlPath = "/";
  43.  
     
  44.  
    OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
  45.  
    bufferedWriter = new BufferedWriter(streamWriter);
  46.  
    bufferedWriter.write("GET " requestUrlPath " HTTP/1.1\r\n");
  47.  
    bufferedWriter.write("Host: " this.host "\r\n");
  48.  
    bufferedWriter.write("\r\n");
  49.  
    bufferedWriter.flush();
  50.  
     
  51.  
    BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
  52.  
    bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
  53.  
    String line = null;
  54.  
    while((line = bufferedReader.readLine())!= null){
  55.  
    System.out.println(line);
  56.  
    }
  57.  
    bufferedReader.close();
  58.  
    bufferedWriter.close();
  59.  
    socket.close();
  60.  
     
  61.  
    }
  62.  
     
  63.  
     
  64.  
    public void sendPost() throws IOException{
  65.  
    String path = "/";
  66.  
    String data = URLEncoder.encode("name", "utf-8") "=" URLEncoder.encode("张三", "utf-8") "&"
  67.  
    URLEncoder.encode("age", "utf-8") "=" URLEncoder.encode("32", "utf-8");
  68.  
    // String data = "name=zhigang_jia";
  69.  
    System.out.println(">>>>>>>>>>>>>>>>>>>>>" data);
  70.  
    OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
  71.  
    bufferedWriter = new BufferedWriter(streamWriter);
  72.  
    bufferedWriter.write("POST " path " HTTP/1.1\r\n");
  73.  
    bufferedWriter.write("Host: " this.host "\r\n");
  74.  
    bufferedWriter.write("Content-Length: " data.length() "\r\n");
  75.  
    bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");
  76.  
    bufferedWriter.write("\r\n");
  77.  
    bufferedWriter.write(data);
  78.  
     
  79.  
    bufferedWriter.write("\r\n");
  80.  
    bufferedWriter.flush();
  81.  
     
  82.  
    BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
  83.  
    bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
  84.  
    String line = null;
  85.  
    while((line = bufferedReader.readLine())!= null)
  86.  
    {
  87.  
    System.out.println(line);
  88.  
    }
  89.  
    bufferedReader.close();
  90.  
    bufferedWriter.close();
  91.  
    socket.close();
  92.  
    }
  93.  
     
  94.  
    public static void main(String[] args) throws Exception {
  95.  
    /**
  96.  
    * http协议测试
  97.  
    */
  98.  
    //SocketForHttpTest forHttpTest = new SocketForHttpTest("www.百度.com", 80);
  99.  
    /**
  100.  
    * https协议测试
  101.  
    */
  102.  
    SocketForHttpTest forHttpTest = new SocketForHttpTest("www.百度.com", 443);
  103.  
    try {
  104.  
    forHttpTest.sendGet();
  105.  
    // forHttpTest.sendPost();
  106.  
    } catch (IOException e) {
  107.  
     
  108.  
    e.printStackTrace();
  109.  
    }
  110.  
    }
  111.  
     
  112.  
    }

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhekfcgb
系列文章
更多 icon
同类精品
更多 icon
继续加载