package com.db;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class RestUtil {
/**
* 實現對REST服務的請求
* @param urlStr
* @param urlParam
* @return
* @throws java.io.IOException
*/
public static String httpGet(String urlStr, List<String> urlParam) throws IOException{
if (!urlParam.isEmpty()) {
urlStr += "?";
// 定義一個迭代器,並將MAP值的集合賦值
for (String string : urlParam) {
urlStr += string + "&";
}
urlStr = urlStr.substring(0, urlStr.length() - 1);
}
// 實例一個URL資源
URL url = new URL(urlStr);
//實例一個HTTP CONNECT
HttpURLConnection connet = (HttpURLConnection) url.openConnection();
connet.setRequestMethod("GET");
connet.setRequestProperty("Charset", "UTF-8");
connet.setRequestProperty("Content-Type", "application/json");
connet.setConnectTimeout(15000);// 連接超時 單位毫秒
connet.setReadTimeout(15000);// 讀取超時 單位毫秒
if(connet.getResponseCode() != 200){
System.out.println("請求異常" + urlStr);
return "";
}
//將返回的值存入到String中
BufferedReader brd = new BufferedReader(new InputStreamReader(connet.getInputStream(),"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = brd.readLine()) != null){
sb.append(line);
}
brd.close();
connet.disconnect();
return sb.toString();
}
}