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:


<network-security-config>
<domain-config usesCleartextTraffic="false">
<domain includeSubdomains="true">example.comdomain>
domain-config>
network-security-config>

Sample code for getting or posting data is as follows:

public class PostCall {
private static final String USER_AGENT = "Mozilla/5.0 (Linux; ; ) AppleWebKit/ (KHTML, like Gecko) Chrome/ Mobile Safari/";

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

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!