Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Https Post request in java

I want to login to application from java code. Here is my code...

String httpsURL = "https://www.abcd.com/auth/login/";

String query = "email="+URLEncoder.encode("[email protected]","UTF-8"); 
query += "&";
query += "password="+URLEncoder.encode("abcd","UTF-8") ;

URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-length", String.valueOf(query.length())); 
con.setRequestProperty("Content-Type","application/x-www- form-urlencoded"); 
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)"); 
con.setDoOutput(true); 
con.setDoInput(true); 

DataOutputStream output = new DataOutputStream(con.getOutputStream());  


output.writeBytes(query);

output.close();

DataInputStream input = new DataInputStream( con.getInputStream() ); 



for( int c = input.read(); c != -1; c = input.read() ) 
System.out.print( (char)c ); 
input.close(); 

System.out.println("Resp Code:"+con .getResponseCode()); 
System.out.println("Resp Message:"+ con .getResponseMessage()); 

but i can not login, it returns back only login page.

If anybody can, please help me to understand what am i doing wrong.

like image 243
Santhosh Avatar asked Aug 03 '11 13:08

Santhosh


People also ask

How do you make a HTTP POST request in Java?

Using java. To get a HttpURLConnection object, simply cast URLConnection instance to a HttpURLConnection . Then to send HTTP POST request, pass POST string literal to the setRequestMethod() method of HttpURLConnection object.

How do I send a payload request in Java?

To send the JSON with payload to the REST API endpoint, you need to enclose the JSON data in the body of the HTTP request and indicate the data type of the request body with the "Content-Type: application/json" request header.

How do I connect to https in Java?

Therefore, if you want to create an HTTPS connection from within your applet code, simply specify HTTPS as your protocol when creating an instance of the URL class: URL url = new URL("https://[your server]");


1 Answers

Wrong :- (Extra space is there in mid of www- form)

con.setRequestProperty("Content-Type","application/x-www- form-urlencoded"); 

Correct

 con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
like image 160
Santhosh Avatar answered Oct 20 '22 05:10

Santhosh