Mercurial Hosting > luan
comparison core/src/luan/modules/UrlCall.java @ 283:b669cdaf54b7
add URL post;
add Http.request.query_string;
add web_run.form();
git-svn-id: https://luan-java.googlecode.com/svn/trunk@284 21e917c8-12df-6dd8-5cb6-c86387c605b9
author | fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9> |
---|---|
date | Tue, 02 Dec 2014 03:34:04 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
282:38bd29e59a6e | 283:b669cdaf54b7 |
---|---|
1 package luan.modules; | |
2 | |
3 import java.io.InputStream; | |
4 import java.io.InputStreamReader; | |
5 import java.io.OutputStream; | |
6 import java.io.Reader; | |
7 import java.io.IOException; | |
8 import java.net.URLConnection; | |
9 import java.net.HttpURLConnection; | |
10 import java.net.URL; | |
11 import java.util.Map; | |
12 import java.util.HashMap; | |
13 | |
14 | |
15 public final class UrlCall { | |
16 public final URLConnection connection; | |
17 | |
18 public UrlCall(String url) throws IOException { | |
19 this(new URL(url)); | |
20 } | |
21 | |
22 public UrlCall(URL url) throws IOException { | |
23 connection = url.openConnection(); | |
24 } | |
25 | |
26 public void acceptJson() { | |
27 connection.setRequestProperty("accept","application/json"); | |
28 } | |
29 | |
30 public String get() throws IOException { | |
31 Reader in = new InputStreamReader(connection.getInputStream()); | |
32 String rtn = Utils.readAll(in); | |
33 in.close(); | |
34 return rtn; | |
35 } | |
36 | |
37 public String post(String content,String contentType) throws IOException { | |
38 HttpURLConnection connection = (HttpURLConnection)this.connection; | |
39 | |
40 connection.setRequestProperty("Content-type",contentType); | |
41 connection.setDoOutput(true); | |
42 connection.setRequestMethod("POST"); | |
43 | |
44 byte[] post = content.getBytes(); | |
45 connection.setRequestProperty("Content-Length",Integer.toString(post.length)); | |
46 OutputStream out = connection.getOutputStream(); | |
47 out.write(post); | |
48 out.flush(); | |
49 | |
50 Reader in; | |
51 try { | |
52 in = new InputStreamReader(connection.getInputStream()); | |
53 } catch(IOException e) { | |
54 InputStream is = connection.getErrorStream(); | |
55 if( is == null ) | |
56 throw e; | |
57 in = new InputStreamReader(is); | |
58 String msg = Utils.readAll(in); | |
59 in.close(); | |
60 throw new UrlCallException(msg,e); | |
61 } | |
62 String rtn = Utils.readAll(in); | |
63 in.close(); | |
64 out.close(); | |
65 return rtn; | |
66 } | |
67 | |
68 public String post(String content) throws IOException { | |
69 return post(content,"application/x-www-form-urlencoded"); | |
70 } | |
71 | |
72 public String postJson(String content) throws IOException { | |
73 return post(content,"application/json"); | |
74 } | |
75 | |
76 public static final class UrlCallException extends IOException { | |
77 UrlCallException(String msg,IOException e) { | |
78 super(msg,e); | |
79 } | |
80 } | |
81 } |