how to make a valid rest call with authentication in Java - java

I am trying to write a java class file that authenticates to a system using a HTTP Rest call )post in this case).
I have tried the following code, but I get an error stating:
{"errors":[{"message":"The request could not be understood","developerMessage":"The request body did not contain valid JSON"}]}
here is my code:
public class simplePost {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws IOException {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://xxxxxx/xxxxx/token");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username", "password"));
List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("username", "xxxxxxxxxx"));
nameValuePairs.add(new BasicNameValuePair("password", "xxxxxx"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
}
I am not sure why I am getting this error.
When I put in the URI and login information in Postman or AdvanceRestClient, I get the proper response.
Can I get a little help on this?
thanks!
ironmantis7x

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.

HttpClient auto logging out when sending post data

I have the method sendPost() which sends a post data to login to a certain site. I am able to get the response code of 302. After executing this method, I have a sendPost2() method which will work if I am successfully logged in. However, I get the response code of 200 in sendPost2(), it also tells me that I am not logged in. It seems that after executing sendPost(), the httpclient logs me out. How do you prevent it from logging out?
Here is my sendPost() but I can't give you a valid username and password:
private void sendPost() throws Exception {
String url = "http://sblive.auf.edu.ph/schoolbliz/commfile/login.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("user_id", "testusername"));
urlParameters.add(new BasicNameValuePair("password", "testpassword"));
urlParameters.add(new BasicNameValuePair("x", "47"));
urlParameters.add(new BasicNameValuePair("y", "1"));
urlParameters.add(new BasicNameValuePair("body_color", "#9FBFD0"));
urlParameters.add(new BasicNameValuePair("welcome_url", "../PARENTS_STUDENTS/main_files/login_success.htm"));
urlParameters.add(new BasicNameValuePair("login_type", "parent_student"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
Recipe
prepare a CookieStore
set it in the HttpContext
pass the context to every HttpClient#execute() call
You need the cookie store to have a place to keep the session ID between calls.
Code
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// ...
HttpResponse response1 = httpClient.execute(method1, httpContext);
// ...
HttpResponse response2 = httpClient.execute(method2, httpContext);
// ...

Java HttpClient: Not able to read json data in the post request

Here I am posting the JSON data using HttpClient. But I am not able to read the data on the other application. When I do request.getParameter("username"), it returns me null. Both my applications are deployed on the same server. Please tell me what I am doing wrong. Thank you
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://localhost:8080/AuthenticationService/UserIdentificationServlet");
postRequest.setHeader("Content-type", "application/json");
StringEntity input = new StringEntity("{\"username\":\""+username+"\"}");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse postResponse = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(new InputStreamReader((postResponse.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
}
If you want to use request.getParameter, then you have to post the data in a URL encoded format.
//this example from apache httpcomponents doc
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);

VIEWSTATE value in the HttpPost

Here is the case, I want to post to a website, but before that I must retrieve the viewstate value and then make the post using this value, but the problem is that viewstate value is changing every time i make posts, so I am a little confused how can I use it's value in the second post if the value on the server will be already different.
Is there any solution or am I doing everything wrong?
main with httppost
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(
"www.website.com/Login.aspx");
String viewstate = getViewState(client, request,
"www.website.com/Login.aspx");
System.out.println(viewstate);
request.getParams().setBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
request.setHeader("Content-Type", "text/html; charset=utf-8");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("__VIEWSTATE",
viewstate))
postParameters.add(new BasicNameValuePair("__EVENTTARGET", ""));
postParameters.add(new BasicNameValuePair("__EVENTARGUMENT", ""));
postParameters.add(new BasicNameValuePair("ctl00$tbUsername",
"name"));
postParameters
.add(new BasicNameValuePair("ctl00$tbPwd", "psw"));
postParameters.add(new BasicNameValuePair("ctl00$chkRememberLogin",
"0"));
postParameters
.add(new BasicNameValuePair("ctl00$cmdLogin", "Login"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
String responseBody2 = EntityUtils.toString(response.getEntity());
System.out.println(responseBody2);
}
// print page wap
// System.out.println(responseBody2);
}
and then send httpget
String html = "";
try {
URL url1 = new URL("www.website.com/Login.aspx");
URLConnection conn = url1.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line+"\n");
}
rd.close();
html = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return findViewstate(html);
So what I was thinking, maybe I should reuse the same httpClient with the cookies or anything, so that the next request will be to the same page...
If I recall correctly ViewState values are encrypted by default and have information in them to prevent tampering, therefore, multiple requests WILL result in different values. But if you do a request, then make a post back to the page as the user would you should be ok, but you will need to make sure that all data goes back or you are going to hit issues with ASP.NET's event validation.

Categories