浅谈Java HttpURLConnection请求方式

作者:ouyangjun__ 时间:2021-06-24 12:34:49 

一)URL代理请求

该方式请求有两种代理方式。

方式一:使用该方式代理之后,之后的所有接口都会使用代理请求


// 对http开启全局代理
System.setProperty("http.proxyHost", "192.168.1.1");
System.setProperty("http.proxyPort", "80");

// 对https开启全局代理
System.setProperty("https.proxyHost", "192.168.1.1");
System.setProperty("https.proxyPort", "80");

方式二:适用于只有部分接口需要代理请求场景


Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("192.168.1.1", 80));
HttpURLConnection conn = null;
try {
 URL url = new URL("http://localhost:8080/ouyangjun");
 conn = (HttpURLConnection) url.openConnection(proxy);
} catch (MalformedURLException e) {
 e.printStackTrace();
} catch (IOException e) {
 e.printStackTrace();
}

二)无参数GET请求

方法解析:

HttpGetUtils.doGetNoParameters(String requestURL, String proxyHost, Integer proxyPort);

requestURL:请求路径,必填

proxyHost: * ,即服务器代理地址,可为null

proxyPort:代理端口,可为null

说明:一般本地测试几乎是不会用代理的,只有服务器用代理方式请求比较多。

实现源码:


package com.ouyangjun.wechat.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;

/**
* http请求工具类
* @author ouyangjun
*/
public class HttpGetUtils {

/**
  * http get请求, 不带参数
  * @param requestURL
  * @param method
  * @return
  */
 public static String doGetNoParameters(String requestURL, String proxyHost, Integer proxyPort) {
   // 记录信息
   StringBuffer buffer = new StringBuffer();

HttpURLConnection conn = null;
   try {
     URL url = new URL(requestURL);
     // 判断是否需要代理模式请求http
     if (proxyHost != null && proxyPort != null) {
       // 如果是本机自己测试, 不需要代理请求,但发到服务器上的时候需要代理请求
       // 对http开启全局代理
       //System.setProperty("http.proxyHost", proxyHost);
       //System.setProperty("http.proxyPort", proxyPort);
       // 对https开启全局代理
       //System.setProperty("https.proxyHost", proxyHost);
       //System.setProperty("https.proxyPort", proxyPort);

// 代理访问http请求
       Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
       conn = (HttpURLConnection) url.openConnection(proxy);
     } else {
       // 原生访问http请求,未代理请求
       conn = (HttpURLConnection) url.openConnection();
     }

// 设置请求的属性
     conn.setDoOutput(true); // 是否可以输出
     conn.setRequestMethod("GET"); // 请求方式, 只包含"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"六种
     conn.setConnectTimeout(60000); // 最高超时时间
     conn.setReadTimeout(60000); // 最高读取时间
     conn.setConnectTimeout(60000); // 最高连接时间

// 读取数据
     InputStream is = null;
     InputStreamReader inputReader = null;
     BufferedReader reader = null;
     try {
       is = conn.getInputStream();
       inputReader = new InputStreamReader(is, "UTF-8");
       reader = new BufferedReader(inputReader);

String temp;
       while ((temp = reader.readLine()) != null) {
         buffer.append(temp);
       }
     } catch (Exception e) {
       System.out.println("HttpGetUtils doGetNoParameters error: " + e);
     } finally {
       try {
         if (reader != null) {
           reader.close();
         }
         if (inputReader != null) {
           inputReader.close();
         }
         if (is != null) {
           is.close();
         }
       } catch (IOException e) {
         System.out.println("HttpGetUtils doGetNoParameters error: " + e);
       }
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     // 当http连接空闲时, 释放资源
     if (conn != null) {
       conn.disconnect();
     }
   }
   // 返回信息
   return buffer.length()==0 ? "" : buffer.toString();
 }
}

三)带参数POST请求

方法解析:

HttpPostUtils.doPost(String requestURL, String params, String proxyHost, Integer proxyPort);

requestURL:请求路径,必填

params:请求参数,必填,数据格式为JSON

proxyHost: * ,即服务器代理地址,可为null

proxyPort:代理端口,可为null

说明:一般本地测试几乎是不会用代理的,只有服务器用代理方式请求比较多。

实现源码:


package com.ouyangjun.wechat.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;

/**
* http请求工具类
* @author ouyangjun
*/
public class HttpPostUtils {

/**
  * http post请求, 带参数
  * @param requestURL
  * @param params
  * @return
  */
 public static String doPost(String requestURL, String params, String proxyHost, Integer proxyPort) {
   // 记录信息
   StringBuffer buffer = new StringBuffer();

HttpURLConnection conn = null;
   try {
     URL url = new URL(requestURL);
     // 判断是否需要代理模式请求http
     if (proxyHost != null && proxyPort != null) {
       // 如果是本机自己测试, 不需要代理请求,但发到服务器上的时候需要代理请求
       // 对http开启全局代理
       //System.setProperty("http.proxyHost", proxyHost);
       //System.setProperty("http.proxyPort", proxyPort);
       // 对https开启全局代理
       //System.setProperty("https.proxyHost", proxyHost);
       //System.setProperty("https.proxyPort", proxyPort);

// 代理访问http请求
       Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
       conn = (HttpURLConnection) url.openConnection(proxy);
     } else {
       // 原生访问http请求,未代理请求
       conn = (HttpURLConnection) url.openConnection();
     }

// 设置请求的属性
     conn.setDoOutput(true); // 是否可以输出
     conn.setRequestMethod("POST"); // 请求方式, 只包含"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"六种
     conn.setConnectTimeout(60000); // 最高超时时间
     conn.setReadTimeout(60000); // 最高读取时间
     conn.setConnectTimeout(60000); // 最高连接时间

conn.setDoInput(true); // 是否可以输入
     if (params != null) {
       // 设置参数为json格式
       conn.setRequestProperty("Content-type", "application/json");

// 写入参数信息
       OutputStream os = conn.getOutputStream();
       try {
         os.write(params.getBytes("UTF-8"));
       } catch (Exception e) {
         System.out.println("HttpPostUtils doPost error: " + e);
       } finally {
         try {
           if (os != null) {
             os.close();
           }
         } catch (IOException e) {
           System.out.println("HttpPostUtils doPost error: " + e);
         }
       }
     }

// 读取数据
     InputStream is = null;
     InputStreamReader inputReader = null;
     BufferedReader reader = null;
     try {
       is = conn.getInputStream();
       inputReader = new InputStreamReader(is, "UTF-8");
       reader = new BufferedReader(inputReader);

String temp;
       while ((temp = reader.readLine()) != null) {
         buffer.append(temp);
       }
     } catch (Exception e) {
       System.out.println("HttpPostUtils doPost error: " + e);
     } finally {
       try {
         if (reader != null) {
           reader.close();
         }
         if (inputReader != null) {
           inputReader.close();
         }
         if (is != null) {
           is.close();
         }
       } catch (IOException e) {
         System.out.println("HttpPostUtils doPost error: " + e);
       }
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     // 当http连接空闲时, 释放资源
     if (conn != null) {
       conn.disconnect();
     }
   }
   // 返回信息
   return buffer.length()==0 ? "" : buffer.toString();
 }
}

四)Http模拟测试

本案例是使用了微信公众号两个接口作为了测试案例。

appID和appsecret需要申请了微信公众号才能获取到。


package com.ouyangjun.wechat.test;
import com.ouyangjun.wechat.utils.HttpGetUtils;
import com.ouyangjun.wechat.utils.HttpPostUtils;

public class TestHttp {

private final static String WECHAT_APPID=""; // appid, 需申请微信公众号才能拿到
 private final static String WECHAT_APPSECRET=""; // appsecret, 需申请微信公众号才能拿到

public static void main(String[] args) {
   // 获取微信公众号token
   getWeChatToken();

// 修改用户备注信息
   String token = "31_1uw5em_HrgkfXok6drZkDZLKsBfbNJr9WTdzdkc_Tdat-9tpOezWsNI6tBMkyPe_zDHjErIS1r0dgnTpT5bfKXcASShJVhPqumivRP21PvQe3Cbfztgs1IL2Jpy7kw3Y09bC1urlWzDA52mtEDGcADAVUX";
   String openid = "oCh4n0-6JKQpJgBOPA5tytoYb0VY";
   updateUserRemark(token, openid);
 }

/**
  * 根据appid和appsecret获取微信token,返回json格式数据,需自行解析
  * @return
  */
 public static String getWeChatToken() {
   String requestURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WECHAT_APPID+"&secret="+WECHAT_APPSECRET;

String token = HttpGetUtils.doGetNoParameters(requestURL, null, null);
   System.out.println("wechat token: " + token);
   return token;
 }

/**
  * 修改用户备注,返回json格式数据,需自行解析
  * @param token
  * @param openid
  * @return
  */
 public static String updateUserRemark(String token, String openid) {
   String reuqestURL = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token="+token;
   // 封装json参数
   String jsonParams = "{\"openid\":\""+openid+"\",\"remark\":\"oysept\"}";

String msg = HttpPostUtils.doPost(reuqestURL, jsonParams, null, null);
   System.out.println("msg: " + msg);
   return jsonParams;
 }
}

补充知识:Java HttpURLConnection post set params 设置请求参数的三种方法 实践总结

我就废话不多说了,大家还是直接看代码吧~


     /**
      * the first way to set params
      * OutputStream
      */

byte[] bytesParams = paramsStr.getBytes();
     // 发送请求params参数
     OutputStream outStream=connection.getOutputStream();
     outStream.write(bytesParams);
     outStream.flush();

/**
      * the second way to set params
      * PrintWriter
      */

PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
     //PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
     // 发送请求params参数
     printWriter.write(paramsStr);
     printWriter.flush();

/**
      * the third way to set params
      * OutputStreamWriter
      */
     OutputStreamWriter out = new OutputStreamWriter(
         connection.getOutputStream(), "UTF-8");
     // 发送请求params参数
     out.write(paramsStr);
     out.flush();

demo:


/**
  * @param pathurl
  * @param paramsStr
  * @return
  */
 private static String postUrlBackStr(String pathurl, String paramsStr) {
   String backStr = "";
   InputStream inputStream = null;
   ByteArrayOutputStream baos = null;
   try {
     URL url = new URL(pathurl);
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     // 设定请求的方法为"POST",默认是GET
     connection.setRequestMethod("POST");
     connection.setConnectTimeout(50000);
     connection.setReadTimeout(50000);
    // User-Agent IE11 的标识
     connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.3; Trident/7.0;rv:11.0)like Gecko");
     connection.setRequestProperty("Accept-Language", "zh-CN");
     connection.setRequestProperty("Connection", "Keep-Alive");
     connection.setRequestProperty("Charset", "UTF-8");
     /**
      * 当我们要获取我们请求的http地址访问的数据时就是使用connection.getInputStream().read()方式时我们就需要setDoInput(true),
      根据api文档我们可知doInput默认就是为true。我们可以不用手动设置了,如果不需要读取输入流的话那就setDoInput(false)。

当我们要采用非get请求给一个http网络地址传参 就是使用connection.getOutputStream().write() 方法时我们就需要setDoOutput(true), 默认是false
      */
     // 设置是否从httpUrlConnection读入,默认情况下是true;
     connection.setDoInput(true);
     // 设置是否向httpUrlConnection输出,如果是post请求,参数要放在http正文内,因此需要设为true, 默认是false;
     connection.setDoOutput(true);
     connection.setUseCaches(false);

/**
      * the first way to set params
      * OutputStream
      */
    /*  byte[] bytesParams = paramsStr.getBytes();
     // 发送请求params参数
     OutputStream outStream=connection.getOutputStream();
     outStream.write(bytesParams);
     outStream.flush();
     */

/**
      * the second way to set params
      * PrintWriter
      */
     /* PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
     //PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
     // 发送请求params参数
     printWriter.write(paramsStr);
     printWriter.flush();*/

/**
      * the third way to set params
      * OutputStreamWriter
      */
     OutputStreamWriter out = new OutputStreamWriter(
         connection.getOutputStream(), "UTF-8");
     // 发送请求params参数
     out.write(paramsStr);
     out.flush();

connection.connect();//
     int contentLength = connection.getContentLength();
     if (connection.getResponseCode() == 200) {
       inputStream = connection.getInputStream();//会隐式调用connect()
       baos = new ByteArrayOutputStream();
       int readLen;
       byte[] bytes = new byte[1024];
       while ((readLen = inputStream.read(bytes)) != -1) {
         baos.write(bytes, 0, readLen);
       }
       backStr = baos.toString();
       Log.i(TAG, "backStr:" + backStr);

} else {
       Log.e(TAG, "请求失败 code:" + connection.getResponseCode());
     }

} catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (baos != null) {
         baos.close();
       }
       if (inputStream != null) {
         inputStream.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return backStr;
 }

来源:https://blog.csdn.net/p812438109/article/details/105105188

标签:Java,HttpURLConnection,请求
0
投稿

猜你喜欢

  • Java对象类型的判断详解

    2023-07-26 09:55:07
  • zookeeper实现分布式锁

    2023-08-03 13:44:18
  • Maven学习----Maven安装与环境变量配置教程

    2021-12-04 08:20:25
  • c# 钩子学习笔记

    2023-03-31 20:54:22
  • C#实现winform中RichTextBox在指定光标位置插入图片的方法

    2022-04-04 01:50:16
  • Go Java算法之找不同示例详解

    2021-10-29 19:37:08
  • Java中Lambda表达式和函数式接口的使用和特性

    2023-06-20 20:05:42
  • SpringBoot整合MongoDB完整实例代码

    2023-10-22 03:42:48
  • C#隐藏控制台键盘输入的方法

    2022-04-29 21:11:06
  • Java 基础之事务详细介绍

    2021-12-16 19:35:36
  • 浅谈C#与Java两种语言的比较

    2023-09-26 13:05:19
  • Java RandomAccessFile 指定位置实现文件读取与写入

    2023-06-05 17:06:25
  • Springmvc发送json数据转Java对象接收

    2023-07-07 16:26:16
  • FastJSON字段智能匹配踩坑的解决

    2022-07-29 19:32:26
  • Java技能点之SimpleDateFormat进行日期格式化问题

    2023-09-09 01:50:26
  • Spring+SpringMVC+MyBatis深入学习及搭建(一)之MyBatis的基础知识

    2021-09-27 15:12:59
  • SpringBoot 上传文件判空以及格式检验流程

    2023-01-19 05:07:36
  • SpringBoot整合Elasticsearch游标查询的示例代码(scroll)

    2022-02-11 02:02:13
  • SpringCloud远程服务调用三种方式及原理

    2023-10-16 07:21:19
  • JAVA中的基本数据类型

    2023-07-29 07:38:34
  • asp之家 软件编程 m.aspxhome.com