I am completely lost on how to send a POST request in Java. I understand how to do in Python with the request module, but no luck with Java. So, I was wondering if anyone could give me a clear example of how this is done via logging into a webpage such as instagram.com. I appreciate all responses. Thanks in advance.
Asked
Active
Viewed 1.4k times
3 Answers
3
if you do not want to use extra library,you can try HttpURLConnection:
public static String doPost(String url, String postData) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// build connection
URLConnection conn = realUrl.openConnection();
// set request properties
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// enable output and input
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
// send POST DATA
out.print(postData);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "/n" + line;
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}

Lyn
- 41
- 1
- 5
-
I see the postData parameter, but how would I go about sending the info per say if the POST paramters for the request are "username" : "someUsername" and "password" : "somePassword" – Kyle Mar 31 '18 at 23:16
-
just like this: String postData = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8"); postData += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); – Lyn Apr 01 '18 at 11:54
2
You can use Spring Web RestTemplate:
new RestTemplate().postForObject(url, requestObject, responseType);

Svichkarev Anatoly
- 684
- 6
- 13
-
1Spring RT for someone who has no clue how to make a simple POST request? It's like saying a 4th grade student could get better in math by working a binomial theorem – Abhijit Sarkar Mar 31 '18 at 23:22
1
you can use OkHttp
https://github.com/square/okhttp
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}

Mateus Gabi
- 99
- 1
- 2