1. 程式人生 > >使用java傳送HTTP請求

使用java傳送HTTP請求

近來在寫專案時呼叫第三方介面,發現使用第三方介面基本都要使用java程式來發送HTTP請求到第三方的伺服器去獲取資料,不同的第三方提供的方法不盡相同,有使用org.apache.commons.httpclient的,有使用org.apache.http.client的,有使用org.codehaus.xfire.client,還有使用org.springframework.web.client的,個人還是比較喜歡使用java原生的java.net.URL與java.net.HttpURLConnection來發送HTTP請求,所以自己寫了一個方法,共饗諸君

public static String sendHttpRequest
(String url, String entity, String method) { BufferedReader bufferedReader = null; URL realUrl; HttpURLConnection conn = null; PrintWriter printWriter = null; String result = ""; try { if ("get".equals(method)) { if (entity != null && !"".equals(entity)) { realUrl = new
URL(url + "?" + entity); } else { realUrl = new URL(url); } // 根據url生成urlConnection物件 conn = (HttpURLConnection) realUrl.openConnection(); /* conn.connect();可以不明文設定連線,conn.getInputStream()會自動連線*/ } else if ("post".equals(method)) { realUrl = new URL(url); conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestMethod("POST");/*設定請求的方法為"POST",預設是GET */ if (entity != null && !"".equals(entity)) { // 設定是否從httpUrlConnection讀入,預設情況下是true; conn.setDoInput(true); /*設定是否向httpUrlConnection輸出,因為這個是post請求,引數要放在 http正文內,因此需要設為true, 預設情況下是false*/ conn.setDoOutput(true); // Post 請求不能使用快取 conn.setUseCaches(false); conn.connect(); printWriter = new PrintWriter(conn.getOutputStream()); printWriter.print(entity); printWriter.flush(); } }else{ throw new IllegalArgumentException("請輸入正確的請求方式"); } bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; if ((line = bufferedReader.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (printWriter != null) { printWriter.close(); } if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException e) { e.printStackTrace(); } return result; } }
測試方法如下:<特意測試了post請求,請求引數為null的情況>
public static void main(String[] args) {
    String str = "userMobile=15539266567&usertype=0";
System.out.println(sendHttpRequest("http://localhost:8080/mine/try", null, "get"));
System.out.println(sendHttpRequest("http://localhost:8080/mine/your/best", str, "post"));
System.out.println(sendHttpRequest("http://localhost:8080/mine/so/amazing", null, "post"));
}
在控制檯列印輸出,哈哈,是不是很完美。關於PUT請求與DELETE請求與POST請求類似,不再敖述。

false
1
{"StageCategory":[{"id":"001","name":"第一階段"},{"id":"002","name":"第二階段"},{"id":"003","name":