您好,登錄后才能下訂單哦!
這篇文章給大家介紹jdk的get和post請求的示例分析,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
OutputStreamWriter out = null; HttpURLConnection conn = null; BufferedReader reader = null; StringBuilder response = new StringBuilder(); URL httpUrl = null; try{ httpUrl = new URL("http://www.baidu.com"); //建立連接 conn = (HttpURLConnection) httpUrl.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setUseCaches(false);//設置不要緩存 conn.setInstanceFollowRedirects(true); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); out = new OutputStreamWriter(conn.getOutputStream()); out.write(params); out.flush(); //讀取響應 reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); response.append(lines); } System.out.println(response.toString()); }catch(Exception e){ e.printStackTrace(); }
/** * 發送GET請求 * * @param url 目的地址 * @param parameters 請求參數,Map類型。 * @return 遠程響應結果 */ public static String sendGet(String url, Map<String, String> parameters) { StringBuilder result = new StringBuilder(); BufferedReader in = null;// 讀取響應輸入流 StringBuilder sbParams = new StringBuilder();// 存儲參數 String params = "";// 編碼之后的參數 try { // 編碼請求參數 for (String name : parameters.keySet()) { sbParams.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8")).append("&"); } String requestParam = sbParams.toString(); params = requestParam.substring(0, requestParam.length() - 1); String fullUrl = url + "?" + params; logger.info("get請求:" + fullUrl); // 創建URL對象 URL connURL = new URL(fullUrl); // 打開URL連接 HttpURLConnection httpConn = (HttpURLConnection) connURL.openConnection(); // 設置通用屬性 httpConn.setRequestProperty("Accept", "*/*"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); // 建立實際的連接 httpConn.connect(); // Map<String, List<String>> headers = httpConn.getHeaderFields(); // 定義BufferedReader輸入流來讀取URL的響應,并設置編碼方式 in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8)); String line; // 讀取返回的內容 while ((line = in.readLine()) != null) { result.append(line); } logger.info("get請求結果:" + result.toString()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result.toString(); }
關于jdk的get和post請求的示例分析就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。