Skip to content

Instantly share code, notes, and snippets.

@superzjn
Created June 10, 2021 16:24
Show Gist options
  • Save superzjn/7bf3b8a8b15f60f60f1572d551f2bb89 to your computer and use it in GitHub Desktop.
Save superzjn/7bf3b8a8b15f60f60f1572d551f2bb89 to your computer and use it in GitHub Desktop.
[HttpUrlConnection] #NetworkIO
public static String fetchHttpContent(String url, String postData, Map<String, String> headers) {
log.debug("url:" + url);
StringBuilder content = new StringBuilder();
try {
Util.disableSSL();
log.debug("start connection to " + url);
java.security.Security.setProperty("networkaddress.cache.ttl", "60");
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestProperty("Accept", CONTENT_TYPE);
con.setRequestMethod(postData == null ? "GET" : "POST");
con.setRequestProperty("Content-Type", CONTENT_TYPE);
con.setDoOutput(postData != null);
con.setConnectTimeout(60 * 1000);
con.setReadTimeout(10 * 60 * 1000);
if (headers != null) {
for (String key : headers.keySet()) {
con.setRequestProperty(key, headers.get(key));
}
}
OutputStream outputStream = null;
if (postData != null) {
outputStream = con.getOutputStream();
outputStream.write(postData.getBytes());
outputStream.flush();
}
boolean isSuccessful = con.getResponseCode() / 100 == 2;
BufferedReader in = new BufferedReader(new InputStreamReader(isSuccessful ? con.getInputStream() : con.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
content.append('\n');
}
in.close();
if (outputStream != null) {
outputStream.close();
}
if (!isSuccessful) {
log.error(content.toString());
}
return isSuccessful ? content.toString() : null;
} catch (FileNotFoundException e) {
log.debug("FileNotFoundException thrown when calling {}", url, e);
} catch (IOException ex) {
log.warn("Exception thrown when calling {}", url, ex);
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment