Send Http Request Get JSON From Servlet in Java Part 1


Hôm nay mình sẻ giới thiệu các bạn đến việc send http request  (GET, POST) thông qua HttpURLConnection để lấy JSON from Servlet ( Action ).

Sourcecode : Bao gồm WEB Servlet + Client + JsonUtils Download

Hình ảnh cấu trúc WebServlet

d1

WEB Servlet chúng ta như sau :


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Person p1 = new Person("ID001", "Kobee", 21);
Person p2 = new Person("ID002", "Jenny", 20);
Person p3 = new Person("ID003", "Ducky", 19);
List<Person> list = new ArrayList<Person>();

list.add(p1);
list.add(p2);
list.add(p3);

PrintWriter out = response.getWriter();
out.print(new JSONArray(list,false));

}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String parameter = request.getParameter("id");
PrintWriter out = response.getWriter();
Person p = null;
if(parameter.equalsIgnoreCase("id001"))
p = new Person("ID001", "Kobee", 21);
JSONObject obj = new JSONObject(p);
out.print(obj.toString());

}

Đầu tiên chúng ta tạo ra 1 servlet MyServlet. Mặc định ví dụ ta có 1 servlet trả vế JSONarray như sau :

d1

Giờ chúng ta sẻ viết 1 lớp HttpParser của chúng ta như sau :

Hình ảnh Project Client.

d1


package demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

public class HttpParser {

	public static void main(String[] args) {
		try {
			HttpParser.getHttpRequestGet_ListPerson();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void getHttpRequestGet_ListPerson() throws Exception{
		// HTTP GET request
		String url = "http://localhost:8080/MyWeb/ActionListPerson";

		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		// optional default is GET
		con.setRequestMethod("GET");

		int responseCode = con.getResponseCode();
		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 result
		//System.out.println(response.toString());
		JSONArray arrPerson = new JSONArray(response.toString());
		for(int i = 0; i < arrPerson.length(); i++){
			JSONObject myPerson = arrPerson.getJSONObject(i);
			System.out.println("ID_ : " + myPerson.getString("id"));
			System.out.println("Name: " + myPerson.getString("name"));
			System.out.println("Age : " + myPerson.getInt("age"));
			System.out.println("=====================================================");
		}
	}

}

Kết quả :
d1

==========================================================================================
Tiếp theo chúng ta sẻ dung Http Post để lấy một Person có ID = ID001.
Tiếp tục viết tiếp cho class HttpParser.java add method sau vào.

// HTTP POST request
	public static void getHttpRequestPOST_ListPerson() throws Exception {
		String url = "http://localhost:8080/MyWeb/ActionListPerson";

		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		con.setRequestMethod("POST");
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

		String urlParameters = "id=id001";

		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		wr.flush();
		wr.close();

		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("Post parameters : " + urlParameters);
		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 result
		JSONObject objPerson = new JSONObject(response.toString());
		System.out.println("ID_ : " + objPerson.getString("id"));
		System.out.println("Name: " + objPerson.getString("name"));
		System.out.println("Age : " + objPerson.getInt("age"));
		System.out.println("=====================================================");

	}

OK đây là kết quả :
d1
Chúc các bạn thành công ^^!

One Response to “Send Http Request Get JSON From Servlet in Java Part 1”


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: