浅谈Java HttpURLConnection请求方式
一)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:代理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; /** * 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:代理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.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; }
以上这篇浅谈java httpurlconnection请求方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇: Shell双引号和单引号有哪些不同
推荐阅读
-
java请求接口的几种方式(java程序开发三个步骤)
-
浅谈Java读写注册表的方式Preferences与jRegistry
-
JAVA发送HTTP请求的四种方式总结
-
微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。
-
【笔记】java http请求 HttpURLConnection 302 重定向
-
Java-Servlet请求方式doXXX、service 具体分析
-
java模拟发送form-data的请求方式
-
浅谈HTTP中GET和POST请求方式的区别
-
浅谈Java代码的 微信长链转短链接口使用 post 请求封装Json(实例)
-
浅谈Java HttpURLConnection请求方式