Last active
August 29, 2015 14:24
-
-
Save fuxingloh/0d01df63cfd7f0ada446 to your computer and use it in GitHub Desktop.
Http Get/Post with Apache Utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
default String connect(String url) throws IOException { | |
try (CloseableHttpClient client = HttpClients.createDefault()){ | |
// Create http post | |
HttpGet get = new HttpGet(url); | |
HttpResponse response = client.execute(get); | |
return EntityUtils.toString(response.getEntity()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String makeRequest() throws IOException { | |
try (CloseableHttpClient client = HttpClients.createDefault()){ | |
// Create http post | |
HttpPost post = new HttpPost("http://"); | |
// Create post string | |
post.setEntity(new StringEntity("something")); | |
HttpResponse response = client.execute(post); | |
return EntityUtils.toString(response.getEntity()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
default String connect(String url, Header[] headers) throws IOException { | |
RequestConfig requestConfig = RequestConfig.custom() | |
.setSocketTimeout(TIMEOUT) | |
.setConnectTimeout(TIMEOUT) | |
.build(); | |
try (CloseableHttpClient client = HttpClientBuilder.create() | |
.setUserAgent(USER_AGENT) | |
.setDefaultRequestConfig(requestConfig).build()){ | |
// Create http post | |
HttpGet get = new HttpGet(url); | |
get.setHeaders(headers); | |
HttpResponse response = client.execute(get); | |
return EntityUtils.toString(response.getEntity()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment