Created
April 29, 2019 00:31
-
-
Save MauOnline/fcb962eabf3e6ff3743689d478e1d6b8 to your computer and use it in GitHub Desktop.
Perform Http request using java.net or Apache HttpClient
This file contains hidden or 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
package ga.summedia.snippets; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.config.RequestConfig; | |
import org.apache.http.client.entity.UrlEncodedFormEntity; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.client.methods.HttpPost; | |
import org.apache.http.entity.BasicHttpEntity; | |
import org.apache.http.entity.BufferedHttpEntity; | |
import org.apache.http.entity.HttpEntityWrapper; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClientBuilder; | |
import org.apache.http.message.BasicNameValuePair; | |
import java.io.*; | |
import java.net.HttpURLConnection; | |
import java.net.MalformedURLException; | |
import java.net.URISyntaxException; | |
import java.net.URL; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Snippets { | |
private final String USER_AGENT = "Mozilla/5.0"; | |
public Snippets() { | |
} | |
public static void main(String... args) { | |
System.out.println("Snippet start..."); | |
final Snippets snippets = new Snippets(); | |
/** | |
* Http requests using HttpUrlConnection from java.net | |
*/ | |
// snippets.sendGETRequestv1("https://www.qwant.com/?q=demica"); | |
// snippets.sendPOSTRequestv1("https://selfsolve.apple.com/wcResults.do"); | |
/** | |
* Http requests using Apache CloseableHttpClient | |
*/ | |
// snippets.sendGETRequestv2("https://www.qwant.com/?q=demica"); | |
snippets.sendPOSTRequestv2("https://selfsolve.apple.com/wcResults.do"); | |
System.out.println("Snippet end..."); | |
} | |
public void sendGETRequestv1(final String url) { | |
try { | |
//Open HTTP connection | |
final URL urlObj = new URL(url); | |
final HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); | |
//Optional: Set HTTP method type (Default is GET) | |
conn.setRequestMethod("GET"); | |
//Add request property | |
conn.setRequestProperty("User-Agent", USER_AGENT); | |
int responseCode = conn.getResponseCode(); | |
System.out.println("Send http GET request..."); | |
System.out.println("Request status..." + responseCode); | |
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); | |
String responseContentLine; | |
StringBuilder responseBody = new StringBuilder(); | |
while ((responseContentLine = bufferedReader.readLine()) != null) { | |
responseBody.append(responseContentLine); | |
} | |
System.out.print(responseBody); | |
bufferedReader.close(); | |
conn.disconnect(); | |
System.out.println("\nRequest completed successfully."); | |
} catch (final MalformedURLException e) { | |
e.printStackTrace(); | |
} catch (final IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public void sendPOSTRequestv1(final String url) { | |
final String urlParams = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; | |
try { | |
//Open HTTP connection | |
final URL urlObj = new URL(url); | |
final HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); | |
//Set HTTP method type as POST (Default is GET) | |
conn.setRequestMethod("POST"); | |
//Add request properties (HEADERS) | |
conn.setRequestProperty("User-Agent", USER_AGENT); | |
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); | |
conn.setDoOutput(true); //Indicates the request is sending out data | |
final DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream()); | |
dataOutputStream.writeBytes(urlParams); | |
dataOutputStream.flush(); | |
dataOutputStream.close(); | |
//Fetch response | |
int responseCode = conn.getResponseCode(); | |
System.out.println("\nSending http POST request...(" + url + ")"); | |
System.out.println("Request parameters...(" + urlParams + ")"); | |
System.out.println("Request status..." + responseCode); | |
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); | |
String responseContentLine; | |
StringBuilder responseBody = new StringBuilder(); | |
while ((responseContentLine = bufferedReader.readLine()) != null) { | |
responseBody.append(responseContentLine); | |
} | |
System.out.print(responseBody); | |
bufferedReader.close(); | |
conn.disconnect(); | |
System.out.println("\nRequest completed successfully."); | |
} catch (final MalformedURLException e) { | |
e.printStackTrace(); | |
} catch (final IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public void sendGETRequestv2(final String url) { | |
//Build client | |
try (final CloseableHttpClient httpClient = HttpClientBuilder.create().setUserAgent(USER_AGENT).build()) { | |
final HttpGet request = new HttpGet(); | |
request.setURI(new URL(url).toURI()); | |
final HttpResponse response = httpClient.execute(request); | |
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); | |
int responseCode = response.getStatusLine().getStatusCode(); | |
System.out.println("Send http GET request...(" + url + ")"); | |
System.out.println("Request status..." + responseCode); | |
String bufferReaderLine; | |
final StringBuilder stringBuilder = new StringBuilder(); | |
while ((bufferReaderLine = bufferedReader.readLine()) != null) { | |
stringBuilder.append(bufferReaderLine); | |
} | |
bufferedReader.close(); | |
System.out.print(response); | |
System.out.println("\nRequest completed successfully."); | |
} catch (final IOException ioE) { | |
ioE.printStackTrace(); | |
} catch (final URISyntaxException e) { | |
e.printStackTrace(); | |
} | |
} | |
public void sendPOSTRequestv2(final String url) { | |
try (final CloseableHttpClient httpClient = HttpClientBuilder.create().setUserAgent(USER_AGENT).build()) { | |
final HttpPost httpPost = new HttpPost(); | |
httpPost.setURI(new URL(url).toURI()); | |
httpPost.setConfig(RequestConfig.custom().setNormalizeUri(true).setRedirectsEnabled(true).build()); | |
final List<NameValuePair> urlParameters = new ArrayList<>(); | |
urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM")); | |
urlParameters.add(new BasicNameValuePair("cn", "")); | |
urlParameters.add(new BasicNameValuePair("locale", "")); | |
urlParameters.add(new BasicNameValuePair("caller", "")); | |
urlParameters.add(new BasicNameValuePair("num", "12345")); | |
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters)); | |
final HttpResponse response = httpClient.execute(httpPost); | |
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); | |
String line; | |
final StringBuilder responseBody = new StringBuilder(); | |
while ((line = bufferedReader.readLine()) != null) { | |
responseBody.append(line); | |
} | |
System.out.print(responseBody); | |
System.out.println("\nRequest completed successfully."); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} catch (URISyntaxException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment