Mercurial Hosting > nabble
comparison src/fschmidt/util/java/UrlCall.java @ 68:00520880ad02
add fschmidt source
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sun, 05 Oct 2025 17:24:15 -0600 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
67:9d0fefce6985 | 68:00520880ad02 |
---|---|
1 package fschmidt.util.java; | |
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 = IoUtils.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 = IoUtils.readAll(in); | |
59 in.close(); | |
60 throw new UrlCallException(msg,e); | |
61 } | |
62 String rtn = IoUtils.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 } |