get post HTTP 請求
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.noahgroup.paas.cicd.dao.model.message.generator.Apollo;
import com.noahgroup.paas.cicd.dao.model.message.generator.NamespaceItem;
import net.sf.json.JSONObject;
public class ApolloUtil {
public static String getApollo(String url, String token) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 開啟和URL之間的連線
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Authorization", token);
connection.connect();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("傳送GET請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
@SuppressWarnings("unchecked")
@JsonIgnoreProperties(ignoreUnknown = true)
public static Apollo jsonToApollo(String json) {
Apollo apollo = new Apollo();
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> map = new HashMap<String, Object>();
map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
List<Map<String, Object>> stages = (List<Map<String, Object>>) map.get("items");
List<NamespaceItem> itemList = new ArrayList<NamespaceItem>();
for (Map<String, Object> stage : stages) {
NamespaceItem namespace = mapper.readValue(mapper.writeValueAsString(stage), NamespaceItem.class);
itemList.add(namespace);
}
apollo.setToken((String)map.get("token"));
apollo.setAppId((String)map.get("appId"));
apollo.setEnv((String)map.get("env"));
apollo.setClusterName((String)map.get("clusterName"));
apollo.setNamespaceName((String)map.get("namespaceName"));
apollo.setComment((String)map.get("comment"));
apollo.setFormat((String)map.get("format"));
String str=String.valueOf(map.get("isPublic"));
if("true".equalsIgnoreCase(str)){
apollo.setIsPublic("公有");
}else {
apollo.setIsPublic("私有");
}
apollo.setDataChangeCreatedBy((String)map.get("dataChangeCreatedBy"));
apollo.setDataChangeLastModifiedBy((String)map.get("dataChangeLastModifiedBy"));
apollo.setDataChangeCreatedTime((String)map.get("dataChangeCreatedTime"));
apollo.setDataChangeLastModifiedTime((String)map.get("dataChangeLastModifiedTime"));
apollo.setItems(itemList);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return apollo;
}
public static String postApollo(String string, String token, JSONObject jsonParam) {
// 獲取連線客戶端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
String entityStr = null;
CloseableHttpResponse response = null;
try {
// 建立POST請求物件
HttpPost httpPost = new HttpPost(string);
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解決中文亂碼問題
httpPost.setEntity(entity);
// 新增請求頭資訊
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.addHeader("Authorization", token);
// 執行請求
response = httpClient.execute(httpPost);
// 獲得響應的實體物件
HttpEntity entity2 = response.getEntity();
// 使用Apache提供的工具類進行轉換成字串
entityStr = EntityUtils.toString(entity2, "UTF-8");
} catch (ClientProtocolException e) {
System.err.println("Http協議出現問題");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("解析錯誤");
e.printStackTrace();
} catch (IOException e) {
System.err.println("IO異常");
e.printStackTrace();
} finally {
// 釋放連線
if (null != response) {
try {
response.close();
httpClient.close();
} catch (IOException e) {
System.err.println("釋放連接出錯");
e.printStackTrace();
}
}
}
return entityStr;
}