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.
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");
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.
Related
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100&_rdr";
String query = "email="+URLEncoder.encode("myemailaddress#gmail.com","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());
![enter image description here](https://i.stack.imgur.com/gVUc3.png)![enter image description here](https://i.stack.imgur.com/3RihL.png)
I made the below 2 changes to your code to make it work:
1) Removed the _rdr parameter from the end of the URL. Looks like when you add that, it always redirects you to the initial page. So:
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100";
2) When following redirects, HttpsURLConnection doesn't set cookies it got from the original response, unless you do this (More info):
CookieHandler.setDefault(new CookieManager());
Putting these two together, we have the final working code below. Here is a working demo. I added BufferedReader to read the response for slightly better looking console output, this is not necessary for it to work.
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100";
String query = "email=" + URLEncoder.encode("myemailaddress#gmail.com", "UTF-8");
CookieHandler.setDefault(new CookieManager());
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();
BufferedReader input = new BufferedReader(new InputStreamReader(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());
I have written a Java Code to test the Watson Question and Answers API. However, I'm getting response code 500, when I run it. I have checked the api url and my login credentials. The problem seems to be somewhere else. Any hints or debugging suggestions would be of great help.
String url = "https://watson-wdc01.ihost.com/instance/526/deepqa/v1/question";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
String userCredentials = "username:password";
String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestProperty("X-SyncTimeout", "30");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestMethod("POST");
String query = "{\"question\": {\"questionText\": \"" + "What are the common respiratory diseases?" + "\"}}";
System.out.println(query);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
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();
//print result
System.out.println(response.toString());
When i open the same url with the browser I get this:
Watson Error!!
Error Encountered!!
Unable to communicate with Watson.
Whats wrong? Could it be something with the configuration? Or is the server down?
Any hints or debugging suggestions would be of great help.
Attempt the same request using your web browser ... or the curl utility.
Capture and output the contents of the error stream.
I don't think that this is the cause of your problems, but it is wrong anyway:
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
You are writing to an API that expects text (JSON). You should therefore use a Writer, not a data (binary) output stream:
Writer wr = new OutputStreamWriter(con.getOutputStream(), "LATIN-1");
wr.write(query);
wr.flush();
I'm running a tomcat servlet on my local machine and an Android emulator with an app that makes a post request to the servlet. The code for the POST is below (without exceptions and the like):
String strUrl = "http://10.0.2.2:8080/DeviceDiscoveryServer/server/devices/";
Device device = Device.getUniqueInstance();
urlParameters += URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(device.getUser(), "UTF-8");
urlParameters += "&" + URLEncoder.encode("port", "UTF-8") + "=" + URLEncoder.encode(new Integer(Device.PORT).toString(), "UTF-8");
urlParameters += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(device.getAddress().getHostAddress(), "UTF-8");
URL url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(urlParameters);
wr.flush();
wr.close();
Whenever this code is executed, the servlet isn't called. However if I change the type of the request to 'GET' and don't write anything to the outputstream, the servlet gets called and everything works fine. Am I just not making the POST correctly or is there some other error?
try the following code, it may help u
try
{
String argUrl =
"";
String requestXml = "";
URL url = new URL( argUrl );
URLConnection con = url.openConnection();
System.out.println("STRING" + requestXml);
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setConnectTimeout( 20000 ); // long timeout, but not infinite
con.setReadTimeout( 20000 );
con.setUseCaches (false);
con.setDefaultUseCaches (false);
// tell the web server what we are sending
con.setRequestProperty ( "Content-Type", "text/xml" );
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write( requestXml );
writer.flush();
writer.close();
// reading the response
InputStreamReader reader = new InputStreamReader( con.getInputStream() );
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf )))
{
buf.append( cbuf, 0, num );
}
String result = buf.toString();
System.err.println( "\nResponse from server after POST:\n" + result );
}
catch( Throwable t )
{
t.printStackTrace( System.out );
}
Out of curiosity I tried getting the response code for my request:
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
This actually made the request go through and I got 200. I checked my Tomcat logs and the request finally got handled. I guess doing url.openConnection() and writing to the OutputStream isn't enough.
As the title says ... I have tried to use the following code to execute a PHP script when user clicks a button in my Java Swing application :
URL url = new URL( "http://www.mywebsite.com/my_script.php" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
But nothing happens ... Is there something wrong ?
I think you're missing the next step which is something like:
InputStream is = conn.getInputStream();
HttpURLConnection basically only opens the socket on connect in order to do something you need to do something like calling getInputStream() or better still getResponseCode()
URL url = new URL( "http://google.com/" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
// do something with the data here
}else{
InputStream err = conn.getErrorStream();
// err may have useful information.. but could be null see javadocs for more information
}
final URL url = new URL("http://domain.com/script.php");
final InputStream inputStream = new InputStreamReader(url);
final BufferedReader reader = new BufferedReader(inputStream).openStream();
String line, response = "";
while ((line = reader.readLine()) != null)
{
response = response + "\r" + line;
}
reader.close();
"response" will hold the text of the page. You may want to play around with the carriage return (depending on the OS, try \n, \r, or a combination of both).
Hope this helps.
I'm a bit new to Java and more to connections stuff with it. I'm trying to create a program to connect to a website ("www.buybackprofesional.com") where I would like to download pictures and get some text from cars (after the login you have to enter a plate number to access a car's file).
This is what I have right now, but it always says that the session has expired, I need a way to login using the username and password of the mainpage, am I right? can someone give me some advice? Thanks
Note: I want to do it in Java, maybe I was not clear in the question.
//URL web = new URL("http://www.buybackprofesional.com/DetallePeri.asp?mat=9073FCV&fec=27/07/2010&tipo=C&modelo=4582&Foto=0");
URL web = new URL("http://www.buybackprofesional.com/");
HttpURLConnection con = (HttpURLConnection) web.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
con.setRequestProperty("Pragma", "no-cache");
con.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
A colleage helped me with this so I'll post the code that works:
public static URLConnection login(String _url, String _username, String _password) throws IOException, MalformedURLException {
String data = URLEncoder.encode("Usuario", "UTF-8") + "=" + URLEncoder.encode(_username, "UTF-8");
data += "&" + URLEncoder.encode("Contrase", "UTF-8") + "=" + URLEncoder.encode(_password, "UTF-8");
// Send data
URL url = new URL(_url);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
return conn;
}
This will submit the form info on the page I need and after that, using cookies I can stay connected!
To connect to a website using java consider using httpunit or httpcore (offered by apache). They handle sessions much better then you (or I) could do on your own.
Edit: Fixed the location of the link. Thanks for the correction!