38

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("abc@xyz.com","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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Santhosh
  • 4,956
  • 12
  • 62
  • 90
  • I suppose you have a form on your login page. If you send the data to the page with the form on it, nothing happens. You have to send the data to the page which you post the form data to. – 11684 Aug 27 '12 at 12:43
  • Warnning: Content-length shall contain the size in bytes. Depending of the content of "query", query.length() and query.getBytes().length may or may not be the same. The later should be used. – Javier Sedano Jan 10 '17 at 14:42

2 Answers2

30

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"); 
sunleo
  • 10,589
  • 35
  • 116
  • 196
Santhosh
  • 4,956
  • 12
  • 62
  • 90
  • both seems same what is the difference ? – sunleo Jul 27 '15 at 08:09
  • 2
    @sunleo I need to send a JSON data as a POST data for a HTTPS request. I tried by converting the JSON to a string and writing it to the outputStream, but the request throws a 400 Status Error. Do anyone know what the error is? – Muthu May 19 '16 at 09:52
  • Maybe you should send not a application/x-www-form-urlencoded, but application/json, as a content-type. – user2501323 Feb 01 '19 at 08:13
0

You could be getting a 400 for a few reasons, but usually becaue the data isn't formatted correctly (maybe it takes XML?). Perhaps a record already existed. Try it using postman to see what result you get.

CoupFlu
  • 311
  • 4
  • 20