Java-Send JSON Request and Read JSON Response
In this video I have shown how to Send a JSON Post request using JAVA and Parse the Response using JAVA.
- For testing we are using the Open web service from this website https://gurujsonrpc.appspot.com.
- In this project we are using 2 jars,
1. java-json.jar
2. org.apache.commons.io.jar - Post_JSON.java
package com.chillyfacts.com; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.apache.commons.io.IOUtils; import org.json.JSONObject; public class Post_JSON { public static void main(String[] args) { Post_JSON.Post_JSON(); } public static void Post_JSON() { String query_url = "https://gurujsonrpc.appspot.com/guru"; String json = "{ \"method\" : \"guru.test\", \"params\" : [ \"jinu awad\" ], \"id\" : 123 }"; try { URL url = new URL(query_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(json.getBytes("UTF-8")); os.close(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); String result = IOUtils.toString(in, "UTF-8"); System.out.println(result); System.out.println("result after Reading JSON Response"); JSONObject myResponse = new JSONObject(result); System.out.println("jsonrpc- "+myResponse.getString("jsonrpc")); System.out.println("id- "+myResponse.getInt("id")); System.out.println("result- "+myResponse.getString("result")); in.close(); conn.disconnect(); } catch (Exception e) { System.out.println(e); } } }
- JSON Request Send
{ "method" : "guru.test", "params" : [ "jinu awad" ], "id" : 123 }
- Console Out Put
{"jsonrpc":"2.0","id":123,"result":"Hello jinu awad!"} result after Reading JSON Response jsonrpc- 2.0 id- 123 result- Hello jinu awad!
-
Download complete project here,
Post_Json_request.rar
0 Comments
Comments
Leave a Comment