JAVA- Send HTTP Get/Post Request and Read JSON response
This tutorial shows how to send HTTP Get Request using java and Read JSON response.
To read json Response you will have to add java-jason.jar to class path.
- Send HTTP Get Request with Parameters.
For testing I have signed UP with http://ipinfodb.com/ which gives the location of IP address for a get request with the API key. The parameters I am passing here is the API key, IP address and the Output format.
Send_HTTP_Request2.javapackage com.chillyfacts.com; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class Send_HTTP_Request2 { public static void main(String[] args) { try { Send_HTTP_Request2.call_me(); } catch (Exception e) { e.printStackTrace(); } } public static void call_me() throws Exception { String url = "http://api.ipinfodb.com/v3/ip-city/?key=d64fcfdfacc213c7ddf4ef911dfe97b55e4696be3532bf8302876c09ebd06b&ip=74.125.45.100&format=json"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print in String System.out.println(response.toString()); //Read JSON response and print JSONObject myResponse = new JSONObject(response.toString()); System.out.println("result after Reading JSON Response"); System.out.println("statusCode- "+myResponse.getString("statusCode")); System.out.println("statusMessage- "+myResponse.getString("statusMessage")); System.out.println("ipAddress- "+myResponse.getString("ipAddress")); System.out.println("countryCode- "+myResponse.getString("countryCode")); System.out.println("countryName- "+myResponse.getString("countryName")); System.out.println("regionName- "+myResponse.getString("regionName")); System.out.println("cityName- "+myResponse.getString("cityName")); System.out.println("zipCode- "+myResponse.getString("zipCode")); System.out.println("latitude- "+myResponse.getString("latitude")); System.out.println("longitude- "+myResponse.getString("longitude")); System.out.println("timeZone- "+myResponse.getString("timeZone")); } }
The JSON response for the above code is shown below.
{ "statusCode" : "OK", "statusMessage" : "", "ipAddress" : "74.125.45.100", "countryCode" : "US", "countryName" : "United States", "regionName" : "Oklahoma", "cityName" : "Tulsa", "zipCode" : "74101", "latitude" : "36.154", "longitude" : "-95.9928", "timeZone" : "-05:00" }
The JAVA Console output will be,
Sending 'GET' request to URL : http://api.ipinfodb.com/v3/ip-city/?key=d64fcfdfacc213c7ddf4ef911dfe97b55e4696be3532bf8302876c09ebad0b&ip=74.125.45.100&format=json Response Code : 200 { "statusCode" : "OK", "statusMessage" : "", "ipAddress" : "74.125.45.100", "countryCode" : "US", "countryName" : "United States", "regionName" : "Oklahoma", "cityName" : "Tulsa", "zipCode" : "74101", "latitude" : "36.154", "longitude" : "-95.9928", "timeZone" : "-05:00"} result after Reading JSON Response statusCode- OK statusMessage- ipAddress- 74.125.45.100 countryCode- US countryName- United States regionName- Oklahoma cityName- Tulsa zipCode- 74101 latitude- 36.154 longitude- -95.9928 timeZone- -05:00
- In the below example I am passing a request to http://httpbin.org/ip. Which will give me a JSON response of my IP address.
Send HTTP Get Request without Parameters.package com.chillyfacts.com; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class Send_HTTP_Request { public static void main(String[] args) { try { Send_HTTP_Request.call_me(); } catch (Exception e) { e.printStackTrace(); } } public static void call_me() throws Exception { String url = "http://httpbin.org/ip"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print in String System.out.println(response.toString()); //Read JSON response and print JSONObject myResponse = new JSONObject(response.toString()); System.out.println("result after Reading JSON Response"); System.out.println("origin- "+myResponse.getString("origin")); } }
JSON output for above request is,
{ "origin": "78.100.209.0" }
Java Console output is,
Sending 'GET' request to URL : http://httpbin.org/ip Response Code : 200 { "origin": "78.100.209.0"} result after Reading JSON Response origin- 78.100.209.0
-
Send_HTTP_Post_Request.java
package com.chillyfacts.com; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.LinkedHashMap; import java.util.Map; import org.json.JSONObject; public class Send_HTTP_Post_Request { public static void main(String[] args) { try { Send_HTTP_Post_Request.call_me(); } catch (Exception e) { e.printStackTrace(); } } public static void call_me() throws Exception { URL url = new URL("https://httpbin.org/post"); Map
params = new LinkedHashMap<>(); params.put("name", "Jinu Jawad"); params.put("email", "helloworld@gmail.com"); params.put("CODE", 1111); params.put("message", "Hello Post Test success"); StringBuilder postData = new StringBuilder(); for (Map.Entry param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); } byte[] postDataBytes = postData.toString().getBytes("UTF-8"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuilder sb = new StringBuilder(); for (int c; (c = in.read()) >= 0;) sb.append((char)c); String response = sb.toString(); System.out.println(response); JSONObject myResponse = new JSONObject(response.toString()); System.out.println("result after Reading JSON Response"); System.out.println("origin- "+myResponse.getString("origin")); System.out.println("url- "+myResponse.getString("url")); JSONObject form_data = myResponse.getJSONObject("form"); System.out.println("CODE- "+form_data.getString("CODE")); System.out.println("email- "+form_data.getString("email")); System.out.println("message- "+form_data.getString("message")); System.out.println("name"+form_data.getString("name")); } } The JSON response for the above code is,
{ "args": {}, "data": "", "files": {}, "form": { "CODE": "1111", "email": "helloworld@gmail.com", "message": "Hello Post Test success", "name": "Jinu Jawad" }, "headers": { "Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Connection": "close", "Content-Length": "86", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "Java/1.8.0_131" }, "json": null, "origin": "78.100.217.219", "url": "http://httpbin.org/post" }
The console output is
result after Reading JSON Response origin- 78.100.217.219 url- http://httpbin.org/post CODE- 1111 email- helloworld@gmail.com message- Hello Post Test success nameJinu Jawad
0 Comments
Comments
Leave a Comment