使用Java原生類庫發送get post請求
-
下面是整個工具的全部代碼,其中用到了
fastjson
:package util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import com.alibaba.fastjson.JSON; public class HttpUtil { public static String sendGet(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回結果字符串 try { // 創建遠程url連接對象 URL url = new URL(httpurl); // 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類 connection = (HttpURLConnection) url.openConnection(); // 設置連接方式:get connection.setRequestMethod("GET"); // 設置連接主機服務器的超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設置讀取遠程返回的數據時間:60000毫秒 connection.setReadTimeout(60000); // 發送請求 connection.connect(); // 通過connection連接,獲取輸入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封裝輸入流is,並指定字符集 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); // 存放數據 StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } connection.disconnect();// 關閉遠程連接 } return result; } public static String sendPost(String URL,Map<String, Object> map){ OutputStreamWriter out = null; BufferedReader in = null; StringBuilder result = new StringBuilder(); HttpURLConnection conn = null; try{ URL url = new URL(URL); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); //發送POST請求必須設置爲true conn.setDoOutput(true); conn.setDoInput(true); //設置連接超時時間和讀取超時時間 conn.setConnectTimeout(30000); conn.setReadTimeout(10000); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); //獲取輸出流 out = new OutputStreamWriter(conn.getOutputStream()); // String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}"; String jsonStr = JSON.toJSONString(map); out.write(jsonStr); out.flush(); out.close(); //取得輸入流,並使用Reader讀取 if (200 == conn.getResponseCode()){ in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null){ result.append(line); } }else{ System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); } }catch (Exception e){ e.printStackTrace(); }finally { try{ if(out != null){ out.close(); } if(in != null){ in.close(); } }catch (IOException ioe){ ioe.printStackTrace(); } } return result.toString(); } }
- 在 2019年9月3日 15:50:51 測試通過,post方法中參數採用
map
類型 兼容性更好,可以和spring
配置使用