How to post&get Data through java.net.HttpURLConnection[Android/Java]

This article describes “How to post Data / get Data through java.net.HttpURLConnection to access the webservice”.


Set allow domain to res/xml/network_security_config.xml:

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config usesCleartextTraffic="false">
<domain includeSubdomains="true">example.com</domain>
</domain-config>
</network-security-config>

Sample code for getting or posting data is as follows:

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
public class PostCall {
private static final String USER_AGENT = "Mozilla/5.0 (Linux; <Android Version>; <Build Tag etc.>) AppleWebKit/<WebKit Rev> (KHTML, like Gecko) Chrome/<Chrome Rev> Mobile Safari/<WebKit Rev>";
public void doSomething() {
String getResult = getUrl(new URL("http://example.com/get_end_point"));
MyRequest request = new MyRequest(something);
String postResult = postJson(new URL(SCRAPED_HTML_URL_END_POINT), new Gson().toJson(request));
String postResult = postJson(new URL("http://example.com/get_end_point"), );
}
private String getUrl(URL url) {
HttpURLConnection c = null;
try{
c = (HttpURLConnection)url.openConnection();
c.setRequestProperty("Content-length", "0");
c.setRequestProperty("User-Agent", USER_AGENT);
c.setRequestMethod("GET");
c.setRequestProperty("Content-Type", "application/json");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(3000);
c.setReadTimeout(3000);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return "";
}
private String postJson(URL url, String json) {
HttpURLConnection c = null;
try{
c = (HttpURLConnection)url.openConnection();
c.setRequestProperty("Content-length", String.valueOf(json.getBytes().length));
c.setRequestProperty("User-Agent", USER_AGENT);
c.setRequestMethod("POST");
c.setRequestProperty("Content-Type", "application/json");
c.setDoInput(true);
c.setDoOutput(true);
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(3000);
c.setReadTimeout(3000);
OutputStream os = c.getOutputStream();
os.write(json.getBytes());
os.flush();
os.close();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return "";
}
}

Create Dummy Endpoint

mockable.io can create your API mock.

Special Thanks