Java,get/post請求
阿新 • • 發佈:2018-11-22
final req cat lin jit tde 遍歷 fault sco
URLConnection
package com.shuzf.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; public class HttpRequestURLConnection { /** * 向指定URL發送GET方法的請求 * *@param url 發送請求的URL * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return URL 所代表遠程資源的響應結果 */ public static String sendGet(String url, String param) { URLConnection conn = null; BufferedReader in = null; String result = ""; try{ String strUrl= url + "?" + param; URL realUrl = new URL(strUrl); // 打開和URL之間的連接 conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立實際的連接 conn.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); 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 e) { e.printStackTrace(); } } return result; } /** * 向指定 URL 發送POST方法的請求 * * @param url 發送請求的 URL * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return 所代表遠程資源的響應結果 */ public static String sendPost(String url, String param) { URLConnection conn = null; PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(param); //flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } public static void main(String[] args) { //發送 GET 請求 String s=HttpRequestURLConnection.sendGet("http://www.baidu.com/abc", "key=123&v=456"); System.out.println(s); //發送 POST 請求 String sr=HttpRequestURLConnection.sendPost("http://www.baidu.com/abc", "key=123&v=456"); System.out.println(sr); } }
HttpURLConnection
package com.shuzf.http; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; public final class HttpRequestHttpURLConnection { //charset=utf-8 必須要,不然會出現亂碼 public static String CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded;charset=utf-8"; public static String CONTENT_TYPE_FORM_DATA = "multipart/form-data;charset=utf-8"; public static String CONTENT_TYPE_JSON = "application/json;charset=utf-8"; public static String CONTENT_TYPE_PLAIN = "text/plain;charset=utf-8"; //輸出所有響應頭字段 private static void headersInfo(HttpURLConnection conn) { Map<String, List<String>> map = conn.getHeaderFields(); // 遍歷所有響應頭字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } } //輸出響應信息 private static void ResponseHeadersInfo(HttpURLConnection conn, URL url) throws IOException { System.out.println("conn.getResponseCode():" + conn.getResponseCode()); System.out.println("conn.getURL():" + conn.getURL()); System.out.println("conn.getRequestMethod():" + conn.getRequestMethod()); System.out.println("conn.getContentType():" + conn.getContentType()); System.out.println("conn.getReadTimeout():" + conn.getReadTimeout()); System.out.println("conn.getResponseMessage():" + conn.getResponseMessage()); System.out.println("url.getDefaultPort():" + url.getDefaultPort()); System.out.println("url.getFile():" + url.getFile()); System.out.println("url.getHost():" + url.getHost()); System.out.println("url.getPath():" + url.getPath()); System.out.println("url.getPort():" + url.getPort()); System.out.println("url.getProtocol():" + url.getProtocol()); System.out.println("url.getQuery():" + url.getQuery()); System.out.println("url.getRef():" + url.getRef()); System.out.println("url.getUserInfo():" + url.getUserInfo()); } /** * @Name: get。 * @Description: 發送get請求,並返回響應數據。 * @Parameters: URL,要訪問的url。 * @Return: String,響應數據。 */ public static String get(String url) { HttpURLConnection conn = null; BufferedReader in = null; try { // 把字符串轉換為URL請求地址 URL realUrl = new URL(url); // 打開連接 conn = (HttpURLConnection)realUrl.openConnection(); // 連接會話 conn.connect(); // 獲取輸入流 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; StringBuilder result = new StringBuilder(); while ((line = in.readLine()) != null) { result.append(line); } return result.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { //關閉流 if (in != null) { in.close(); } // 銷毀連接 if (conn != null) { conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * post。 * @Description: 發送post請求,並返回響應數據。 * @Parameters: URL,要訪問的url。 * @Parameters: parms,訪問參數,Map形式。 * @Return: String,響應數據。 */ public static String post(String URL, Map<String, String> params) { StringBuilder parm = new StringBuilder(); //IsEmpty()是Java中用於判斷某種容器是否有元素的系統庫函數 if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { parm.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } } return post(URL, parm.toString()); } /** * @Name: post。 * @Description: 發送post請求,並返回響應數據。 * @Parameters: URL,要訪問的url。 * @Parameters: parm,訪問參數。 * @Return: String,響應數據。 */ public static String post(String url, String parm) { HttpURLConnection conn = null; // 數據輸出流,輸出參數信息 DataOutputStream out = null; // 數據輸入流,處理服務器響應數據 BufferedReader in = null; try { URL realUrl = new URL(url); // 將url以open方法返回的urlConnection連接強轉為HttpURLConnection連接(標識一個url所引用的遠程對象連接) // 此時cnnection只是為一個連接對象,待連接中 conn = (HttpURLConnection) realUrl.openConnection(); // 設置連接輸出流為true,默認false (post請求是以流的方式隱式的傳遞參數) conn.setDoOutput(true); // 設置連接輸入流為true conn.setDoInput(true); // 設置請求方式為post conn.setRequestMethod("POST"); // post請求緩存設為false conn.setUseCaches(false); // 設置該HttpURLConnection實例是否自動執行重定向 conn.setInstanceFollowRedirects(true); // 設置內容的類型,設置為經過urlEncoded編碼過的from參數 conn.setRequestProperty("Content-Type", HttpRequestHttpURLConnection.CONTENT_TYPE_FORM_URLENCODED); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0; Windows NT 5.1;SV1)"); // 建立連接 // (請求未開始,直到connection.getInputStream()方法調用時才發起,以上各個參數設置需在此方法之前進行) conn.connect(); // 創建輸入輸出流,用於往連接裏面輸出攜帶的參數,(輸出內容為?後面的內容) out = new DataOutputStream(conn.getOutputStream()); // 向對象輸出流寫出數據,這些數據將存到內存緩沖區中 out.writeBytes(parm != null ? parm : ""); // 刷新對象輸出流,將任何字節都寫入潛在的流中 out.flush(); //輸出響應信息 ResponseHeadersInfo(conn, realUrl); // 連接發起請求,處理服務器響應 (從連接獲取到輸入流並包裝為bufferedReader) in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; // 用來存儲響應數據 StringBuilder result = new StringBuilder(); // 循環讀取流 while ((line = in.readLine()) != null) { result .append(line).append(System.getProperty("line.separator")); } return result.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { //關閉流 if (out != null) { out.close(); } //關閉流 if (in != null) { in.close(); } // 銷毀連接 if (conn != null) { conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return null; } public static void main(String[] args) { String result = post("http://vehicle.test.qingmiaojituan.com/api/user/info", "token=Vk1fMjAxODAzMTMxNDE0NDVfNDQ5MjU4N18zNDYyNTE%3D"); System.out.println("\n" + result); } }
Java,get/post請求