电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

淺談Java HttpURLConnection請(qǐng)求方式

瀏覽:2日期:2022-08-26 11:07:23

一)URL代理請(qǐng)求

該方式請(qǐng)求有兩種代理方式。

方式一:使用該方式代理之后,之后的所有接口都會(huì)使用代理請(qǐng)求

// 對(duì)http開(kāi)啟全局代理System.setProperty('http.proxyHost', '192.168.1.1');System.setProperty('http.proxyPort', '80'); // 對(duì)https開(kāi)啟全局代理System.setProperty('https.proxyHost', '192.168.1.1');System.setProperty('https.proxyPort', '80');

方式二:適用于只有部分接口需要代理請(qǐng)求場(chǎng)景

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();}

二)無(wú)參數(shù)GET請(qǐng)求

方法解析:

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

requestURL:請(qǐng)求路徑,必填

proxyHost:代理IP,即服務(wù)器代理地址,可為null

proxyPort:代理端口,可為null

說(shuō)明:一般本地測(cè)試幾乎是不會(huì)用代理的,只有服務(wù)器用代理方式請(qǐng)求比較多。

實(shí)現(xiàn)源碼:

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請(qǐng)求工具類(lèi) * @author ouyangjun */public class HttpGetUtils { /** * http get請(qǐng)求, 不帶參數(shù) * @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); // 判斷是否需要代理模式請(qǐng)求http if (proxyHost != null && proxyPort != null) {// 如果是本機(jī)自己測(cè)試, 不需要代理請(qǐng)求,但發(fā)到服務(wù)器上的時(shí)候需要代理請(qǐng)求// 對(duì)http開(kāi)啟全局代理//System.setProperty('http.proxyHost', proxyHost);//System.setProperty('http.proxyPort', proxyPort);// 對(duì)https開(kāi)啟全局代理//System.setProperty('https.proxyHost', proxyHost);//System.setProperty('https.proxyPort', proxyPort); // 代理訪問(wèn)http請(qǐng)求Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));conn = (HttpURLConnection) url.openConnection(proxy); } else {// 原生訪問(wèn)http請(qǐng)求,未代理請(qǐng)求conn = (HttpURLConnection) url.openConnection(); }// 設(shè)置請(qǐng)求的屬性 conn.setDoOutput(true); // 是否可以輸出 conn.setRequestMethod('GET'); // 請(qǐng)求方式, 只包含'GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'六種 conn.setConnectTimeout(60000); // 最高超時(shí)時(shí)間 conn.setReadTimeout(60000); // 最高讀取時(shí)間 conn.setConnectTimeout(60000); // 最高連接時(shí)間// 讀取數(shù)據(jù) 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 { // 當(dāng)http連接空閑時(shí), 釋放資源 if (conn != null) {conn.disconnect(); } } // 返回信息 return buffer.length()==0 ? '' : buffer.toString(); }}

三)帶參數(shù)POST請(qǐng)求

方法解析:

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

requestURL:請(qǐng)求路徑,必填

params:請(qǐng)求參數(shù),必填,數(shù)據(jù)格式為JSON

proxyHost:代理IP,即服務(wù)器代理地址,可為null

proxyPort:代理端口,可為null

說(shuō)明:一般本地測(cè)試幾乎是不會(huì)用代理的,只有服務(wù)器用代理方式請(qǐng)求比較多。

實(shí)現(xiàn)源碼:

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請(qǐng)求工具類(lèi) * @author ouyangjun */public class HttpPostUtils { /** * http post請(qǐng)求, 帶參數(shù) * @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); // 判斷是否需要代理模式請(qǐng)求http if (proxyHost != null && proxyPort != null) {// 如果是本機(jī)自己測(cè)試, 不需要代理請(qǐng)求,但發(fā)到服務(wù)器上的時(shí)候需要代理請(qǐng)求// 對(duì)http開(kāi)啟全局代理//System.setProperty('http.proxyHost', proxyHost);//System.setProperty('http.proxyPort', proxyPort);// 對(duì)https開(kāi)啟全局代理//System.setProperty('https.proxyHost', proxyHost);//System.setProperty('https.proxyPort', proxyPort); // 代理訪問(wèn)http請(qǐng)求Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));conn = (HttpURLConnection) url.openConnection(proxy); } else {// 原生訪問(wèn)http請(qǐng)求,未代理請(qǐng)求conn = (HttpURLConnection) url.openConnection(); }// 設(shè)置請(qǐng)求的屬性 conn.setDoOutput(true); // 是否可以輸出 conn.setRequestMethod('POST'); // 請(qǐng)求方式, 只包含'GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'六種 conn.setConnectTimeout(60000); // 最高超時(shí)時(shí)間 conn.setReadTimeout(60000); // 最高讀取時(shí)間 conn.setConnectTimeout(60000); // 最高連接時(shí)間conn.setDoInput(true); // 是否可以輸入 if (params != null) {// 設(shè)置參數(shù)為json格式conn.setRequestProperty('Content-type', 'application/json'); // 寫(xiě)入?yún)?shù)信息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); }} }// 讀取數(shù)據(jù) 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 { // 當(dāng)http連接空閑時(shí), 釋放資源 if (conn != null) {conn.disconnect(); } } // 返回信息 return buffer.length()==0 ? '' : buffer.toString(); }}

四)Http模擬測(cè)試

本案例是使用了微信公眾號(hào)兩個(gè)接口作為了測(cè)試案例。

appID和appsecret需要申請(qǐng)了微信公眾號(hào)才能獲取到。

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, 需申請(qǐng)微信公眾號(hào)才能拿到 private final static String WECHAT_APPSECRET=''; // appsecret, 需申請(qǐng)微信公眾號(hào)才能拿到 public static void main(String[] args) { // 獲取微信公眾號(hào)token getWeChatToken(); // 修改用戶備注信息 String token = '31_1uw5em_HrgkfXok6drZkDZLKsBfbNJr9WTdzdkc_Tdat-9tpOezWsNI6tBMkyPe_zDHjErIS1r0dgnTpT5bfKXcASShJVhPqumivRP21PvQe3Cbfztgs1IL2Jpy7kw3Y09bC1urlWzDA52mtEDGcADAVUX'; String openid = 'oCh4n0-6JKQpJgBOPA5tytoYb0VY'; updateUserRemark(token, openid); } /** * 根據(jù)appid和appsecret獲取微信token,返回json格式數(shù)據(jù),需自行解析 * @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格式數(shù)據(jù),需自行解析 * @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參數(shù) String jsonParams = '{'openid':''+openid+'','remark':'oysept'}'; String msg = HttpPostUtils.doPost(reuqestURL, jsonParams, null, null); System.out.println('msg: ' + msg); return jsonParams; }}

補(bǔ)充知識(shí):Java HttpURLConnection post set params 設(shè)置請(qǐng)求參數(shù)的三種方法 實(shí)踐總結(jié)

我就廢話不多說(shuō)了,大家還是直接看代碼吧~

/** * the first way to set params * OutputStream */ byte[] bytesParams = paramsStr.getBytes(); // 發(fā)送請(qǐng)求params參數(shù) 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')); // 發(fā)送請(qǐng)求params參數(shù) printWriter.write(paramsStr); printWriter.flush(); /** * the third way to set params * OutputStreamWriter */ OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream(), 'UTF-8'); // 發(fā)送請(qǐng)求params參數(shù) 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(); // 設(shè)定請(qǐng)求的方法為'POST',默認(rèn)是GET connection.setRequestMethod('POST'); connection.setConnectTimeout(50000); connection.setReadTimeout(50000); // User-Agent IE11 的標(biāo)識(shí) 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'); /** * 當(dāng)我們要獲取我們請(qǐng)求的http地址訪問(wèn)的數(shù)據(jù)時(shí)就是使用connection.getInputStream().read()方式時(shí)我們就需要setDoInput(true), 根據(jù)api文檔我們可知doInput默認(rèn)就是為true。我們可以不用手動(dòng)設(shè)置了,如果不需要讀取輸入流的話那就setDoInput(false)。 當(dāng)我們要采用非get請(qǐng)求給一個(gè)http網(wǎng)絡(luò)地址傳參 就是使用connection.getOutputStream().write() 方法時(shí)我們就需要setDoOutput(true), 默認(rèn)是false */ // 設(shè)置是否從httpUrlConnection讀入,默認(rèn)情況下是true; connection.setDoInput(true); // 設(shè)置是否向httpUrlConnection輸出,如果是post請(qǐng)求,參數(shù)要放在http正文內(nèi),因此需要設(shè)為true, 默認(rèn)是false; connection.setDoOutput(true); connection.setUseCaches(false); /** * the first way to set params * OutputStream */ /* byte[] bytesParams = paramsStr.getBytes(); // 發(fā)送請(qǐng)求params參數(shù) 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')); // 發(fā)送請(qǐng)求params參數(shù) printWriter.write(paramsStr); printWriter.flush();*/ /** * the third way to set params * OutputStreamWriter */ OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream(), 'UTF-8'); // 發(fā)送請(qǐng)求params參數(shù) out.write(paramsStr); out.flush(); connection.connect();// int contentLength = connection.getContentLength(); if (connection.getResponseCode() == 200) {inputStream = connection.getInputStream();//會(huì)隱式調(diào)用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, '請(qǐng)求失敗 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請(qǐng)求方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 温州中研白癜风专科_温州治疗白癜风_温州治疗白癜风医院哪家好_温州哪里治疗白癜风 | FFU_空气初效|中效|高效过滤器_空调过滤网-广州梓净净化设备有限公司 | 板框压滤机-隔膜压滤机-厢式压滤机生产厂家-禹州市君工机械设备有限公司 | 山东钢格板|栅格板生产厂家供应商-日照森亿钢格板有限公司 | 变位机,焊接变位机,焊接变位器,小型变位机,小型焊接变位机-济南上弘机电设备有限公司 | 高压绝缘垫-红色配电房绝缘垫-绿色高压绝缘地毯-上海苏海电气 | 六维力传感器_三维力传感器_二维力传感器-南京神源生智能科技有限公司 | 天津试验仪器-电液伺服万能材料试验机,恒温恒湿标准养护箱,水泥恒应力压力试验机-天津鑫高伟业科技有限公司 | 底部填充胶_电子封装胶_芯片封装胶_芯片底部填充胶厂家-东莞汉思新材料 | 医养体检包_公卫随访箱_慢病随访包_家签随访包_随访一体机-济南易享医疗科技有限公司 | 火锅底料批发-串串香技术培训[川禾川调官网] | 蚂蚁分类信息系统 - PHP同城分类信息系统 - MayiCMS | 语料库-提供经典范文,文案句子,常用文书,您的写作得力助手 | 矿用履带式平板车|探水钻机|气动架柱式钻机|架柱式液压回转钻机|履带式钻机-启睿探水钻机厂家 | 能耗监测系统-节能监测系统-能源管理系统-三水智能化 | 铝机箱_铝外壳加工_铝外壳厂家_CNC散热器加工-惠州市铂源五金制品有限公司 | 北京网站建设首页,做网站选【优站网】,专注北京网站建设,北京网站推广,天津网站建设,天津网站推广,小程序,手机APP的开发。 | 气象监测系统_气象传感器_微型气象仪_气象环境监测仪-山东风途物联网 | 组织研磨机-高通量组织研磨仪-实验室多样品组织研磨机-东方天净 传递窗_超净|洁净工作台_高效过滤器-传递窗厂家广州梓净公司 | 应急灯_消防应急灯_应急照明灯_应急灯厂家-大成智慧官网 | 成都软件开发_OA|ERP|CRM|管理系统定制开发_成都码邻蜀科技 | 洁净实验室工程-成都手术室净化-无尘车间装修-四川华锐净化公司-洁净室专业厂家 | 德州网站开发定制-小程序开发制作-APP软件开发-「两山开发」 | 广州印刷厂_广州彩印厂-广州艺彩印务有限公司 | 天津暖气片厂家_钢制散热器_天津铜铝复合暖气片_维尼罗散热器 | 青岛侦探_青岛侦探事务所_青岛劝退小三_青岛婚外情取证-青岛王军侦探事务所 | 打造全球沸石生态圈 - 国投盛世 锂电混合机-新能源混合机-正极材料混料机-高镍,三元材料混料机-负极,包覆混合机-贝尔专业混合混料搅拌机械系统设备厂家 | 超声波反应釜【百科】-以马内利仪器| 哈尔滨京科脑康神经内科医院-哈尔滨治疗头痛医院-哈尔滨治疗癫痫康复医院 | 维泰克Veertek-锂电池微短路检测_锂电池腐蚀检测_锂电池漏液检测 | 烟台游艇培训,威海游艇培训-烟台市邮轮游艇行业协会 | 天津热油泵_管道泵_天津高温热油泵-天津市金丰泰机械泵业有限公司【官方网站】 | EPDM密封胶条-EPDM密封垫片-EPDM生产厂家 | 仓储笼_金属箱租赁_循环包装_铁网箱_蝴蝶笼租赁_酷龙仓储笼租赁 测试治具|过炉治具|过锡炉治具|工装夹具|测试夹具|允睿自动化设备 | 电动卫生级调节阀,电动防爆球阀,电动软密封蝶阀,气动高压球阀,气动对夹蝶阀,气动V型调节球阀-上海川沪阀门有限公司 | 砂石生产线_石料生产线设备_制砂生产线设备价格_生产厂家-河南中誉鼎力智能装备有限公司 | 有机肥设备生产制造厂家,BB掺混肥搅拌机、复合肥设备生产线,有机肥料全部加工设备多少钱,对辊挤压造粒机,有机肥造粒设备 -- 郑州程翔重工机械有限公司 | 直齿驱动-新型回转驱动和回转支承解决方案提供商-不二传动 | 山西3A认证|太原AAA信用认证|投标AAA信用证书-山西AAA企业信用评级网 | 贴片电感_贴片功率电感_贴片绕线电感_深圳市百斯特电子有限公司 贴片电容代理-三星电容-村田电容-风华电容-国巨电容-深圳市昂洋科技有限公司 | 防火阀、排烟防火阀、电动防火阀产品生产销售商-德州凯亿空调设备有限公司 |