日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HttpUtils工具类

發布時間:2023/12/31 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HttpUtils工具类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述 作為一個java開發,自己肯定寫過或者用過HttpUtils用來發送http請求吧,而且肯定也見過各種五花八門的工具類吧,而且每個都不一樣,內心有沒有寫一個相對標準的工具類的想法呢?反正我自己是有這種想法的,畢竟Http是有標準的,剛好機會來了,就按照自己理解的標準去寫了,分享一下,當然也會提供一些比較容易擴展的方式,畢竟每個人的需求都是不同的。 前面會用一定的篇幅講述一下我所依賴的“標準”到底是什么樣的,后面再貼代碼。Http的四要素 眾所周知,Http是基于TCP,而TCP是用來傳輸數據的,說得再通俗一些,就是用來傳遞字符串的。那么這個字符串到底要如何傳遞以及如何解析,這就是應用層協議需要設計的,我們平時見到的應用層協議都是圍繞“如何來傳遞字符串”這個目標然后實現的(如何傳遞也意味著如何解析),Http也是,它的標準就是4要素,或者是4塊內容。1.請求行 請求行占了一行,格式是:方法 請求地址 HTTP/版本號后面中間分別有1個空格 2.請求頭 這個是多行,每一行都是key:value的形式 3.空行 就是一個空行,用于區分請求頭和請求體 4.請求體 請求體就是我們常說的body或者form部分了。這個行數不定,那如何知道結尾了呢?就要用請求頭里面所標記的Content-Length來判斷了,用一些框架在解析的時候,如何發現Length的長度和請求體的長度不一致的時候,就會出現異常。包括接收Http請求或者請求http的時候。對于Http的響應也是這4要素。 Http傳遞參數的方式 其實HttpUtils要解決的問題就是http參數傳遞的問題,因此想寫出好的工具類,那就必須知道所有的傳參方式,哪怕自己不用,也可以不寫,但得知道。上面花那么多篇幅講4要素,順便也把所有的參數傳遞方式講了一遍,我這邊總結一下,下面的幾種參數,只有請求體里面只能允許一種情況存在,其它的都可以存在。請求方法,這也算參數吧,因為在用的時候需要用。 請求地址。 路徑參數。 請求頭參數。 請求體參數。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();// 設置通用的請求屬性connection.setRequestProperty("accept","*/*");connection.setRequestProperty("connection","Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 建立實際的連接connection.connect();// 獲取所有響應頭字段Map<String, List<String>> map = connection.getHeaderFields();// 遍歷所有的響應頭字段for (String key : map.keySet()) {System.out.println(key + "--->" + map.get(key));}// 定義 BufferedReader輸入流來讀取URL的響應in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("發送GET請求出現異常!" + e);e.printStackTrace();}// 使用finally塊來關閉輸入流finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}/*** 發送請求,如果失敗,會返回null** @param url* @param map* @return*/public static String post(String url, Map<String, String> map) {// 處理請求地址try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpPost post = new HttpPost(uri);// 添加參數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));// 執行請求HttpResponse response = client.execute(post);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);}} catch (Exception e) {e.printStackTrace();} finally {// 關閉流if (in != null) {try {in.close();} catch (Exception e) {e.printStackTrace();}}}return buffer.toString();} else {return null;}} catch (Exception e1) {e1.printStackTrace();}return null;}/*** 發送請求,如果失敗,會返回null** @param url* @param map* @return*/public static StringBuffer postbuffer(String url, Map<String, String> map) {// 處理請求地址try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpPost post = new HttpPost(uri);// 添加參數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));// 執行請求HttpResponse response = client.execute(post);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);}} catch (Exception e) {e.printStackTrace();} finally {// 關閉流if (in != null) {try {in.close();} catch (Exception e) {e.printStackTrace();}}}return buffer;} else {return null;}} catch (Exception e1) {e1.printStackTrace();}return null;}/*** 發送請求,如果失敗會返回null** @param url* @param str* @return*/public static String post(String url, String str) {// 處理請求地址try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpPost post = new HttpPost(uri);post.setEntity(new StringEntity(str, Charset));// 執行請求HttpResponse response = client.execute(post);if (response.getStatusLine().getStatusCode() == 200) {// 處理請求結果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 {// 關閉流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) {// 處理請求地址try {HttpClient client = HttpClientBuilder.create().build();URI uri = new URI(url);HttpPost post = new HttpPost(uri);post.setEntity(new StringEntity(str, Charset));// 執行請求HttpResponse response = client.execute(post);if (response.getStatusLine().getStatusCode() == 200) {// 處理請求結果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 {// 關閉流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 = "";// 返回的結果BufferedReader in = null;// 讀取響應輸入流try {//創建連接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)");//防止報403錯誤。connection.connect();//POST請求BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));out.write(param);out.flush();out.close();//讀取響應// 定義BufferedReader輸入流來讀取URL的響應,并設置編碼方式in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));String line;// 讀取返回的內容while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {e.printStackTrace();System.out.println("Http請求方法內部問題");} finally {try {if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}return result;}/*** 發送GET方式的請求,并返回結果字符串。** @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;} 總結 HttpUtils一個很常用的工具類,非原創有借鑒https://blog.csdn.net/ywg_1994/article/details/104487216文章,介紹很詳細可以看看

總結

以上是生活随笔為你收集整理的HttpUtils工具类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。