Send Get request java
Below is sample java program to send get request. We will send get request to Google search with single parameter and read the search results from response:
package com.javahonk; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; public class SendGetRequest { public static void main(String[] args) { sendGetRequest(); } private static void sendGetRequest() { URL url = null; BufferedReader bufferedReader = null; try { //If your company has proxy server in place then //please enter detail of proxy server to send //request otherwise you will get an error Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy_server_name", 8080)); url = new URL("http://www.google.com/search?" + "q=javahonk.com"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(proxy); //Without proxy server un-comment below to send request //comment out above proxy server configuration /*url = new URL("http://www.google.com/search?q=javahonk"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();*/ httpURLConnection.setRequestMethod("GET"); httpURLConnection.setRequestProperty("User-Agent", "Firefox/21.0"); int responseCode = httpURLConnection.getResponseCode(); System.out.println("Sending get request... \n"); System.out.println("Got response... \n"); System.out.println("Response Code is: " + responseCode+"\n"); System.out.println("Read response... \n"); bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); String lineRead; StringBuffer response = new StringBuffer(); while ((lineRead = bufferedReader.readLine()) != null) { response.append(lineRead); } System.out.println("Response is below... \n"); System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Output: