Java HttpURLConnection如何实现请求方式探讨?

2026-05-21 10:011阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计987个文字,预计阅读时间需要4分钟。

Java HttpURLConnection如何实现请求方式探讨?

一、URL代理请求+该方式请求有两种代理方式。方式一:使用该方式代理后,之后的所有接口都会使用代理请求。// 对http开启全局代理System.setProperty(http.proxyHost, 192.168.1.1); System.se...

一)URL代理请求

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

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

// 对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:代理IP,即服务器代理地址,可为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; /** * 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 = "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:

Java HttpURLConnection如何实现请求方式探讨?

/** * @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; }

以上这篇浅谈Java HttpURLConnection请求方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

本文共计987个文字,预计阅读时间需要4分钟。

Java HttpURLConnection如何实现请求方式探讨?

一、URL代理请求+该方式请求有两种代理方式。方式一:使用该方式代理后,之后的所有接口都会使用代理请求。// 对http开启全局代理System.setProperty(http.proxyHost, 192.168.1.1); System.se...

一)URL代理请求

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

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

// 对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:代理IP,即服务器代理地址,可为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; /** * 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 = "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:

Java HttpURLConnection如何实现请求方式探讨?

/** * @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; }

以上这篇浅谈Java HttpURLConnection请求方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。