HttpClient auto logging out when sending post data - java

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);
// ...

Related

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.

apache http client send url encoded post request

I have a dropwizard service in whitch i implemented a post request who consumes APPLICATION_FORM_URLENCODED media type and uses #FormParam annotation
Then in my client i'm using Apache HttpClient to make a post request like this:
public void sendPost(String path, JsonObject params) throws Exception {
String url = "http://" + TS_API_HOST + ":" + TS_API_PORT + "/" + path;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<String> keys = params.keySet().iterator();
while(keys.hasNext()){
String currentKey = keys.next();
nvps.add(new BasicNameValuePair(currentKey, params.get(currentKey).toString()));
}
System.out.println(nvps.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response.close();
}
}
The url and params I'm passing are correct but i keep getting 400 bad request as a response.
In Postman it works very well...

how to make a valid rest call with authentication in 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

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);

Android, Java: HTTP POST Request

I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.
POST /login/dologin HTTP/1.1
Host: webservice.companyname.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
id=username&num=password&remember=on&output=xml
The XML Response that i will be getting is
<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
<message><![CDATA[]]></message>
<status><![CDATA[true]]></status>
<Rlo><![CDATA[Username]]></Rlo>
<Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc>
<Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm>
<Rl><![CDATA[username#company.com]]></Rl>
<uid><![CDATA[3539145]]></uid>
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>
This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair.
An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.
to #BalusC answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
Here is an example of convertStramToString.
Please consider using HttpPost. Adopt from this: http://www.javaworld.com/javatips/jw-javatip34.html
URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);
// Encode according to application/x-www-form-urlencoded specification
String content =
"id=" + URLEncoder.encode ("username") +
"&num=" + URLEncoder.encode ("password") +
"&remember=" + URLEncoder.encode ("on") +
"&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Try this should be the length of you content.
// it is not neccessary equal to 48.
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length);
// Write body
OutputStream output = connection.getOutputStream();
output.write(content.getBytes());
output.close();
You will need to catch the exception yourself.
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
Try HttpClient for Java:
http://hc.apache.org/httpclient-3.x/
You can reuse the implementation I added to ACRA:
http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236
(See the doPost(Map, Url) method, working over http and https even with self signed certs)
I used the following code to send HTTP POST from my android client app to C# desktop app on my server:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I worked on reading the request from a C# app on my server (something like a web server little application).
I managed to read request posted data using the following code:
server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();
HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;
StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();
HTTP request POST in java does not dump the answer?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
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()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

Categories