Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Send HTTP POST/GET request using HttpURLConnection in java
package com.hprog99;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("GET Request Using HttpURLConnection");
http.sendGet();
System.out.println();
System.out.println("POST Request Using HttpURLConnection");
http.sendPost();
}
// HTTP GET request
private void sendGet() throws Exception {
String username="hitenpratap";
StringBuilder stringBuilder = new StringBuilder("https://twitter.com/search");
stringBuilder.append("?q=");
stringBuilder.append(URLEncoder.encode(username, "UTF-8"));
URL obj = new URL(stringBuilder.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
connection.setRequestProperty("Accept-Charset", "UTF-8");
System.out.println("\nSending request to URL : " + url);
System.out.println("Response Code : " + con.getResponseCode());
System.out.println("Response Message : " + con.getResponseMessage());
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
System.out.println(response.toString());
}
private void sendPost() throws Exception {
StringBuilder tokenUri=new StringBuilder("param1=");
tokenUri.append(URLEncoder.encode("params1","UTF-8"));
tokenUri.append("&param2=");
tokenUri.append(URLEncoder.encode("param2","UTF-8"));
tokenUri.append("&param3=");
tokenUri.append(URLEncoder.encode("param3","UTF-8"));
String url = "https://example.com";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "UTF-8");
con.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
outputStreamWriter.write(params.toString());
outputStreamWriter.flush();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
@GardOlsen

This comment has been minimized.

Copy link

@GardOlsen GardOlsen commented Dec 30, 2015

Thanks for this. I was able to do my first Java send post with this :D I've added some suggestion to the comment.

Line 79: params does not exist.
Line 84: urlParameters does not exist.

With the tokenUri it's easier to read if was like this:
StringBuilder tokenUri=new StringBuilder("param1=");
tokenUri.append(URLEncoder.encode("value1","UTF-8"));
tokenUri.append("&param2=");
tokenUri.append(URLEncoder.encode("value2","UTF-8"));
tokenUri.append("&param3=");
tokenUri.append(URLEncoder.encode("value3","UTF-8"));

Cheers

@ArashBabazade

This comment has been minimized.

Copy link

@ArashBabazade ArashBabazade commented Sep 19, 2016

Thank you it really helped

@asifali9145

This comment has been minimized.

Copy link

@asifali9145 asifali9145 commented Oct 24, 2016

on line 40 connection.setRequestProperty("Accept-Charset", "UTF-8");
in this line you use "connection" where is it define in code or is it a java class, if it is java class so how i get its scope?

@yehia

This comment has been minimized.

Copy link

@yehia yehia commented Feb 21, 2018

how to open another page?????

@RepakaRamateja

This comment has been minimized.

Copy link

@RepakaRamateja RepakaRamateja commented Feb 28, 2018

I am unable to send the parameters still through the post request even thought i used URLencoder

any help ??

@amithanamakkanavar

This comment has been minimized.

Copy link

@amithanamakkanavar amithanamakkanavar commented Mar 20, 2018

This code worked for me

            URL url = new URL("https://ai.web.com/nov/index.php");
	Map<String,Object> params = new LinkedHashMap<>();
	params.put("accessid", "asasasasas");
	params.put("uid", "sasasasa");
	params.put("uname", "asasaa");
	params.put("agent", "sasasasasaddd");
	params.put("query", "adewewewe");
            StringBuilder postData = new StringBuilder();
	for (Map.Entry<String,Object> param : params.entrySet()) {
		if (postData.length() != 0) postData.append('&');
		postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
		postData.append('=');
		postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
	}
	byte[] postDataBytes = postData.toString().getBytes("UTF-8");
	HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	conn.setRequestMethod("POST");
	conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
	conn.setDoOutput(true);
	conn.getOutputStream().write(postDataBytes);
	Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
	StringBuilder data = new StringBuilder();
	for (int c; (c = in.read()) >= 0;) {
		data.append((char)c);
	}
	String intentData = data.toString();
	System.out.println(intentData);	
@Marcelo-Machado

This comment has been minimized.

Copy link

@Marcelo-Machado Marcelo-Machado commented Sep 24, 2018

I was able to post the post, but I can not read the json return in php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment