HttpUtils工具类
生活随笔
收集整理的這篇文章主要介紹了
HttpUtils工具类
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
概述
作為一個(gè)java開發(fā),自己肯定寫過(guò)或者用過(guò)HttpUtils用來(lái)發(fā)送http請(qǐng)求吧,而且肯定也見(jiàn)過(guò)各種五花八門的工具類吧,而且每個(gè)都不一樣,內(nèi)心有沒(méi)有寫一個(gè)相對(duì)標(biāo)準(zhǔn)的工具類的想法呢?反正我自己是有這種想法的,畢竟Http是有標(biāo)準(zhǔn)的,剛好機(jī)會(huì)來(lái)了,就按照自己理解的標(biāo)準(zhǔn)去寫了,分享一下,當(dāng)然也會(huì)提供一些比較容易擴(kuò)展的方式,畢竟每個(gè)人的需求都是不同的。
前面會(huì)用一定的篇幅講述一下我所依賴的“標(biāo)準(zhǔn)”到底是什么樣的,后面再貼代碼。Http的四要素
眾所周知,Http是基于TCP,而TCP是用來(lái)傳輸數(shù)據(jù)的,說(shuō)得再通俗一些,就是用來(lái)傳遞字符串的。那么這個(gè)字符串到底要如何傳遞以及如何解析,這就是應(yīng)用層協(xié)議需要設(shè)計(jì)的,我們平時(shí)見(jiàn)到的應(yīng)用層協(xié)議都是圍繞“如何來(lái)傳遞字符串”這個(gè)目標(biāo)然后實(shí)現(xiàn)的(如何傳遞也意味著如何解析),Http也是,它的標(biāo)準(zhǔn)就是4要素,或者是4塊內(nèi)容。1.請(qǐng)求行
請(qǐng)求行占了一行,格式是:方法 請(qǐng)求地址 HTTP/版本號(hào)后面中間分別有1個(gè)空格
2.請(qǐng)求頭
這個(gè)是多行,每一行都是key:value的形式
3.空行
就是一個(gè)空行,用于區(qū)分請(qǐng)求頭和請(qǐng)求體
4.請(qǐng)求體
請(qǐng)求體就是我們常說(shuō)的body或者form部分了。這個(gè)行數(shù)不定,那如何知道結(jié)尾了呢?就要用請(qǐng)求頭里面所標(biāo)記的Content-Length來(lái)判斷了,用一些框架在解析的時(shí)候,如何發(fā)現(xiàn)Length的長(zhǎng)度和請(qǐng)求體的長(zhǎng)度不一致的時(shí)候,就會(huì)出現(xiàn)異常。包括接收Http請(qǐng)求或者請(qǐng)求http的時(shí)候。對(duì)于Http的響應(yīng)也是這4要素。
Http傳遞參數(shù)的方式
其實(shí)HttpUtils要解決的問(wèn)題就是http參數(shù)傳遞的問(wèn)題,因此想寫出好的工具類,那就必須知道所有的傳參方式,哪怕自己不用,也可以不寫,但得知道。上面花那么多篇幅講4要素,順便也把所有的參數(shù)傳遞方式講了一遍,我這邊總結(jié)一下,下面的幾種參數(shù),只有請(qǐng)求體里面只能允許一種情況存在,其它的都可以存在。請(qǐng)求方法,這也算參數(shù)吧,因?yàn)樵谟玫臅r(shí)候需要用。
請(qǐng)求地址。
路徑參數(shù)。
請(qǐng)求頭參數(shù)。
請(qǐng)求體參數(shù)。HttpUtils的代碼
public static String sendGet(String url, String param) {String result = "";BufferedReader in = null;try {String urlNameString = url + "?" + param;URL realUrl = new URL(urlNameString);// 打開和URL之間的連接URLConnection connection = realUrl.openConnection();// 設(shè)置通用的請(qǐng)求屬性connection.setRequestProperty("accept","*/*");connection.setRequestProperty("connection","Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 建立實(shí)際的連接connection.connect();// 獲取所有響應(yīng)頭字段Map<String, List<String>> map = connection.getHeaderFields();// 遍歷所有的響應(yīng)頭字段for (String key : map.keySet()) {System.out.println(key + "--->" + map.get(key));}// 定義 BufferedReader輸入流來(lái)讀取URL的響應(yīng)in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("發(fā)送GET請(qǐng)求出現(xiàn)異常!" + e);e.printStackTrace();}// 使用finally塊來(lái)關(guān)閉輸入流finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}/*** 發(fā)送請(qǐng)求,如果失敗,會(huì)返回null** @param url* @param map* @return*/public static String post(String url, Map<String, String> map) {// 處理請(qǐng)求地址try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpPost post = new HttpPost(uri);// 添加參數(shù)List<NameValuePair> params = new ArrayList<NameValuePair>();for (String str : map.keySet()) {params.add(new BasicNameValuePair(str, map.get(str)));}post.setEntity(new UrlEncodedFormEntity(params, Charset));// 執(zhí)行請(qǐng)求HttpResponse response = client.execute(post);if (response.getStatusLine().getStatusCode() == 200) {// 處理請(qǐng)求結(jié)果StringBuffer buffer = new StringBuffer();InputStream in = null;try {in = response.getEntity().getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line);}} catch (Exception e) {e.printStackTrace();} finally {// 關(guān)閉流if (in != null) {try {in.close();} catch (Exception e) {e.printStackTrace();}}}return buffer.toString();} else {return null;}} catch (Exception e1) {e1.printStackTrace();}return null;}/*** 發(fā)送請(qǐng)求,如果失敗,會(huì)返回null** @param url* @param map* @return*/public static StringBuffer postbuffer(String url, Map<String, String> map) {// 處理請(qǐng)求地址try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpPost post = new HttpPost(uri);// 添加參數(shù)List<NameValuePair> params = new ArrayList<NameValuePair>();for (String str : map.keySet()) {params.add(new BasicNameValuePair(str, map.get(str)));}post.setEntity(new UrlEncodedFormEntity(params, Charset));// 執(zhí)行請(qǐng)求HttpResponse response = client.execute(post);if (response.getStatusLine().getStatusCode() == 200) {// 處理請(qǐng)求結(jié)果StringBuffer buffer = new StringBuffer();InputStream in = null;try {in = response.getEntity().getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line);}} catch (Exception e) {e.printStackTrace();} finally {// 關(guān)閉流if (in != null) {try {in.close();} catch (Exception e) {e.printStackTrace();}}}return buffer;} else {return null;}} catch (Exception e1) {e1.printStackTrace();}return null;}/*** 發(fā)送請(qǐng)求,如果失敗會(huì)返回null** @param url* @param str* @return*/public static String post(String url, String str) {// 處理請(qǐng)求地址try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpPost post = new HttpPost(uri);post.setEntity(new StringEntity(str, Charset));// 執(zhí)行請(qǐng)求HttpResponse response = client.execute(post);if (response.getStatusLine().getStatusCode() == 200) {// 處理請(qǐng)求結(jié)果StringBuffer buffer = new StringBuffer();InputStream in = null;try {in = response.getEntity().getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line);}} finally {// 關(guān)閉流if (in != null) {in.close();}}return buffer.toString();} else {return null;}} catch (Exception e) {e.printStackTrace();}return null;}public static StringBuffer postbuffer(String url, String str) {// 處理請(qǐng)求地址try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpPost post = new HttpPost(uri);post.setEntity(new StringEntity(str, Charset));// 執(zhí)行請(qǐng)求HttpResponse response = client.execute(post);if (response.getStatusLine().getStatusCode() == 200) {// 處理請(qǐng)求結(jié)果StringBuffer buffer = new StringBuffer();InputStream in = null;try {in = response.getEntity().getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line);}} finally {// 關(guān)閉流if (in != null) {in.close();}}return buffer;} else {return null;}} catch (Exception e) {e.printStackTrace();}return null;}public static String post2(String curl, String param) {String result = "";// 返回的結(jié)果BufferedReader in = null;// 讀取響應(yīng)輸入流try {//創(chuàng)建連接URL url = new URL(curl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestMethod("POST");connection.setUseCaches(false);connection.setInstanceFollowRedirects(true);connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)");//防止報(bào)403錯(cuò)誤。connection.connect();//POST請(qǐng)求BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));out.write(param);out.flush();out.close();//讀取響應(yīng)// 定義BufferedReader輸入流來(lái)讀取URL的響應(yīng),并設(shè)置編碼方式in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));String line;// 讀取返回的內(nèi)容while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {e.printStackTrace();System.out.println("Http請(qǐng)求方法內(nèi)部問(wèn)題");} finally {try {if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}return result;}/*** 發(fā)送GET方式的請(qǐng)求,并返回結(jié)果字符串。** @param url* @return 如果失敗,返回為null*/public static String get(String url) {try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpGet get = new HttpGet(uri);HttpResponse response = client.execute(get);if (response.getStatusLine().getStatusCode() == 200) {StringBuffer buffer = new StringBuffer();InputStream in = null;try {in = response.getEntity().getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line);}} finally {if (in != null) {in.close();}}return buffer.toString();} else {return null;}} catch (Exception e) {e.printStackTrace();}return null;}
總結(jié)
HttpUtils一個(gè)很常用的工具類,非原創(chuàng)有借鑒https://blog.csdn.net/ywg_1994/article/details/104487216文章,介紹很詳細(xì)可以看看
總結(jié)
以上是生活随笔為你收集整理的HttpUtils工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 拳王虚拟项目公社:如何搭建虚拟资源解析站
- 下一篇: 你是一名技术管理者还是项目管理者?