Google authentication with Java apache http tokens - java

I'm trying to authenticate with Google using a simple Java program. I post to the correct URL with my credentials. I get a response with HTTP status code 200 but that doesn't contain any of the authentication tokens that I need to retrieve feeds for the user. Here's the code
private static String postData = "https://www.google.com/accounts/ClientLogin?Content-type=application/x-www-form-urlencoded&accountType=GOOGLE&Email=xxxxxxxx&Passwd=xxxxx";
public GoogleConnector(){
HttpClient client=new DefaultHttpClient();
HttpPost method=new HttpPost(postData);
try{
HttpResponse response=client.execute(method);
System.out.println(response.toString());
}
catch(Exception e){
}

Ok, the first problem you have is that 'Content-Type' needs to be a header, not a request parameter. And secondly, POST parameters should be appended to the request body, not to the request URL. Your code should look something like this:
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost("https://www.google.com/accounts/ClientLogin");
method.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(4);
postParams.add(new BasicNameValuePair("accountType", "GOOGLE"));
postParams.add(new BasicNameValuePair("Email", "xxxxxxx"));
postParams.add(new BasicNameValuePair("Passwd", "xxxxxx"));
postParams.add(new BasicNameValuePair("service", "cl"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams);
method.setEntity(formEntity);
HttpResponse response=client.execute(method);
System.out.println(response.toString());

Related

HTTP Post request and parsing the response in Java

I am trying to create a simple post request to a web API and parse the response received. After quite a lot of search, I was able to come up with the following code:
public class access {
public static void main(String[] args) {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://xxxxx/RSAM_API/api/Logon");
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Request parameters and other properties.
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(2);
urlParameters.add(new BasicNameValuePair("UserId", "xxxxxx"));
urlParameters.add(new BasicNameValuePair("Password", "xxxxxxx"));
try {
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while(null !=(line=rd.readLine())){
System.out.println(line);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
In the above code, I am doing an post request to the URL login endpoint. the response I see after parsing it is:
An error occurred, please try again or contact the administrator with this error id, 26225
I am able to login to the URL through the browser manually. Not sure where I am going wrong in the code.
Is my approach correct in the first place? Can I be sure that my code is right? If it is, why is the response an error?
Any help would be appreciated. Thank you.

Unable to make http POST request in java?

static HttpClient httpclient = new DefaultHttpClient();
static HttpPost httppost = new HttpPost("http://servername:6405/biprws/logon/long");
public static void main(String[] args) throws ClientProtocolException, IOException {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userName", "Administrator"));
postParameters.add(new BasicNameValuePair("password", "test"));
postParameters.add(new BasicNameValuePair("auth", "secEnterprise"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
httppost.addHeader("accept", "application/json");
httppost.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(httppost);
Header s = response.getFirstHeader("logontoken");
String s1 = s.getValue();
System.out.println(s1);// null pointer exception here
}
Running the code above i am not able to add request body to the POST request. How can i achieve this?
Alternative method i followed:
HttpClient client1 = new DefaultHttpClient();
HttpPost post = new HttpPost("http://servername:6405/biprws/logon/long");
String json = "{\"UserName\":\"Administrator\",\"Password\":\"test\",\"Auth\":\"secEnterprise\"}";
StringEntity entity = new StringEntity(json,"UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
System.out.println(entity);
post.setHeader("Accept", "application/json");
HttpResponse response = client1.execute(post);
BufferedReader rd1 = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String result1 = null;
String line1 = "";
result1 = rd1.readLine();
System.out.println(result1);
Still i am not able to make request.
You are successfully receiving a response which does not contain the "logontoken" header. Very possibly because the response is not an HTTP 200 OK response. Why? We don't know, it all depends on the protocol that your server implements on top of HTTP.
That having been said, the use of both httppost.setEntity(new UrlEncodedFromEntity(postParameters)) and httppost.addHeder("Content-Type", "application/json") does not look right to me. A URL-encoded form entity is not of json content type. So, either convert your post parameters to json, or lose the content-type header.

Use Java to get Github repositories

I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.

Post request to server. Different responses with different defaultClients

When i try to send post request using Java (JVM on Mac) with correct credentials I got correct response code 302 FOUND.
But when using the same code on the android, with SAME correct params, i got response CODE 200 OK.
Code to send post request:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(POST_URL);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("auth", "login"));
nvps.add(new BasicNameValuePair("login", login));
nvps.add(new BasicNameValuePair("password", password));
nvps.add(new BasicNameValuePair("set_cookie", "on"));
httpost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
302 FOUND is the common way of doing a "redirection", it seems Android or MacJVM is not performing that redirection. Are you using the same SDK version?
Try to use :
final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);

Log-in Webpage has hidden token that gets sent in a POST when submitting form. How to use the token in a Java HttpPost?

So there is this website that has a login form. I want to log in and then download a file. When submitting the form, not only do username and password get transmitted in the http POST but also a token that is in a hidden <input> tag.
Now, my Problem is that whenever I open the URL in java and get the token to make a POST the token is invalid when I use a HttpClient.
I somehow need to use the same client for calling the website to get the token and making the post. Unfortunately I get a 403 FORBIDDEN return code when trying to access the file.
This is what I have so far:
public static void main(String[] args){
try {
String token = getTokenFromPage("http://my.url");
HttpContext context = new BasicHttpContext();
DefaultHttpClient client = new DefaultHttpClient();
List <NameValuePair> parameters = new ArrayList <NameValuePair>();
HttpPost post = new HttpPost("http://my.url");
parameters.add(new BasicNameValuePair("username", "MYNAME"));
parameters.add(new BasicNameValuePair("password", "MYPW"));
parameters.add(new BasicNameValuePair("token", token));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
post.setEntity(entity);
System.out.println("URL: " + post.getURI());
HttpResponse postResponse = client.execute(post, context);
System.out.println(postResponse.getStatusLine());
EntityUtils.consume(postResponse.getEntity());
//Now download the file
HttpGet httpget = new HttpGet("http://url.to.file");
HttpResponse getResponse = client.execute(httpget, context);
System.out.println(getResponse.toString());
System.out.print((postResponse.getEntity().getContent()));
client.getConnectionManager().shutdown();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You are going to have to make an HTTP request for the login page, parse the resulting HTML in the HTTP response stream, and get the token value to use from there. Using a library like jsoup to parse the HTML would be advisable.

Categories