Wednesday, May 18, 2016

Sử dụng Java console application để gọi Restful service

Tạo restful service như sau
rest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Path("product")
public class Product {
    @Context
    private UriInfo context;
    /** Creates a new instance of Product */
    public Product() {
    }
    @GET
    @Path("/{id}")
    @Produces("application/json")
    public String getJson(@PathParam("id") int id, @QueryParam("name")String name) {
        try {
            JSONObject json = new JSONObject();
            json.put("id", id);
            json.put("name", name);
            return json.toString();
        } catch (Exception e) {
            return "";
        }
    }
    @POST
    @Produces("application/json")
    public String postJson(@FormParam("id") int id, @FormParam("name")String name) {
        try {
            JSONObject json = new JSONObject();
            json.put("id", id);
            json.put("name", name);
            return json.toString();
        } catch (Exception e) {
            return "";
        }
    }
}
Sử dụng thư viện Java kết nối và gọi dịch vụ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public class JavaApplication1 {
    public static void main(String[] args) {
        String address = "http://localhost:8080/WebApplication1/rest/product";
        postData(address);
        getData(address);
    }
    public static void getData(String address) {
        try {
            // cho nguoi dung nhap lieu
            System.out.print("Input id:");
            Scanner sn = new Scanner(System.in);
            address += "/" + URLEncoder.encode(sn.nextLine(),"UTF8");
            System.out.print("Input name:");
            address += "?name=" + URLEncoder.encode(sn.nextLine(),"UTF8");
            // goi yeu cau theo pp get
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            // nhan du lieu
            InputStream response = conn.getInputStream();
            // xu ly du lieu tra ve   
            StringBuilder sb = new StringBuilder();
            for (int c; (c = response.read()) >= 0;) {
                sb.append((char) c);
            }
            System.out.println("Recieve data with get method:" + sb.toString());
        } catch (Exception e) {
            System.out.println("Err:" + e.toString());
        }
    }
    public static void postData(String address) {
        try {
            // ket noi voi server
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            // tao cac tham so se goi len server
            Map<String, Object> params = new LinkedHashMap<String, Object>();
            System.out.print("Input id:");
            Scanner sn = new Scanner(System.in);
            params.put("id", sn.nextLine());
            System.out.print("Input name:");
            params.put("name", sn.nextLine());
            // ghep tham so   
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, Object> 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");
            // ghi du lieu len server (submit)
            conn.setDoOutput(true);
            conn.getOutputStream().write(postDataBytes);
            // nhan du lieu
            InputStream response = conn.getInputStream();
            StringBuilder sb = new StringBuilder();
            for (int c; (c = response.read()) >= 0;) {
                sb.append((char) c);
            }
            System.out.println("Recieve data with post method:" + sb.toString());
        } catch (Exception e) {
            System.out.println("Err:" + e.toString());
        }
    }
}
Mã nguồn ==> ma nguon

Translate