comparison core/src/luan/modules/url/UrlCall.java @ 727:d6a191618c60

minor
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 10 Jun 2016 14:55:26 -0600
parents core/src/luan/modules/UrlCall.java@b669cdaf54b7
children
comparison
equal deleted inserted replaced
726:14f136a4641f 727:d6a191618c60
1 // not used, just for reference
2
3 package luan.modules.url;
4
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.io.OutputStream;
8 import java.io.Reader;
9 import java.io.IOException;
10 import java.net.URLConnection;
11 import java.net.HttpURLConnection;
12 import java.net.URL;
13 import java.util.Map;
14 import java.util.HashMap;
15 import luan.modules.Utils;
16
17
18 public final class UrlCall {
19 public final URLConnection connection;
20
21 public UrlCall(String url) throws IOException {
22 this(new URL(url));
23 }
24
25 public UrlCall(URL url) throws IOException {
26 connection = url.openConnection();
27 }
28
29 public void acceptJson() {
30 connection.setRequestProperty("accept","application/json");
31 }
32
33 public String get() throws IOException {
34 Reader in = new InputStreamReader(connection.getInputStream());
35 String rtn = Utils.readAll(in);
36 in.close();
37 return rtn;
38 }
39
40 public String post(String content,String contentType) throws IOException {
41 HttpURLConnection connection = (HttpURLConnection)this.connection;
42
43 connection.setRequestProperty("Content-type",contentType);
44 connection.setDoOutput(true);
45 connection.setRequestMethod("POST");
46
47 byte[] post = content.getBytes();
48 connection.setRequestProperty("Content-Length",Integer.toString(post.length));
49 OutputStream out = connection.getOutputStream();
50 out.write(post);
51 out.flush();
52
53 Reader in;
54 try {
55 in = new InputStreamReader(connection.getInputStream());
56 } catch(IOException e) {
57 InputStream is = connection.getErrorStream();
58 if( is == null )
59 throw e;
60 in = new InputStreamReader(is);
61 String msg = Utils.readAll(in);
62 in.close();
63 throw new UrlCallException(msg,e);
64 }
65 String rtn = Utils.readAll(in);
66 in.close();
67 out.close();
68 return rtn;
69 }
70
71 public String post(String content) throws IOException {
72 return post(content,"application/x-www-form-urlencoded");
73 }
74
75 public String postJson(String content) throws IOException {
76 return post(content,"application/json");
77 }
78
79 public static final class UrlCallException extends IOException {
80 UrlCallException(String msg,IOException e) {
81 super(msg,e);
82 }
83 }
84 }