JAVA發送post和get請求__JAVA
最後更新:2018-07-27
來源:互聯網
上載者:User
public static String doGet(String url) throws Exception{
String result="";
try {
System.out.println("send get request:"+url);
URL restServiceURL = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Accept", "application/json");
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String output;
while ((output = responseBuffer.readLine()) != null) {
result += output;
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String doPost(String url, Map<String, Object> params) throws Exception{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 開啟和URL之間的串連
URLConnection 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());
// 發送請求參數
StringBuffer sb = new StringBuffer();
for(String key: params.keySet()){
sb.append("&"+key+"="+params.get(key));
}
sb.deleteCharAt(0);
out.print(sb);
// flush輸出資料流的緩衝
out.flush();
// 定義BufferedReader輸入資料流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
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;
}