import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class JiraUtil {
private static final String JIRA_URI = "http://xxx.xxx.xx";
private static final String AUTH = "Basic xxx";
private static final String DEFAULT_ENCODING = "UTF-8";
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36";
private static final String DEFUALT_CONTENT_TYPE = "application/json";
private static final int DEFAULT_SOCKET_TIMEOUT = 10000;
private static Logger logger = LoggerFactory.getLogger(JiraUtil.class);
private JiraUtil(){
}
private static String sendGetRequest(String url, String encoding){
String responseContent = null; //响应内容try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader(HTTP.USER_AGENT, USER_AGENT);
httpGet.setHeader(HTTP.CONTENT_TYPE, DEFUALT_CONTENT_TYPE);
httpGet.setHeader("Authorization", AUTH);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
.setConnectTimeout(
DEFAULT_SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpGet);
int rspCode = response.getStatusLine().getStatusCode();
if (rspCode != 200) {
logger.error(
"Response code is " + rspCode + " instead of 200. Url: " + httpGet.getURI().toString());
}
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, encoding == null ? DEFAULT_ENCODING : encoding);
close(entity);
}
response.close();
} catch (ClientProtocolException e) {
logger.error(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
logger.warn(e.getMessage());
e.printStackTrace();
}
return responseContent;
}
public static ArrayList getAllProjectNames() {
String url = JIRA_URI + "/rest/api/2/project";
String responseContent = sendGetRequest(url,DEFAULT_ENCODING);
JSONArray jsonArray = new JSONArray(responseContent);
ArrayList res = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++){
res.add((String) jsonArray.getJSONObject(i).get("name"));
}
return res;
}
private static void close(HttpEntity entity) {
if (entity == null) {
return;
}
if (entity.isStreaming()) {
try {
final InputStream inStream = entity.getContent();
if (inStream != null) {
inStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}