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.
Related
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.
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.
I am trying to make a HTTP PATCH request in Java, but despite my efforts this is not working.
I am trying to PATCH a Json, here is my code:
HttpResponse response = null;
BufferedReader rd = null;
StringBuffer result = new StringBuffer();
String line = "";
HttpClient httpclient = HttpClients.createDefault();
HttpPatch httpPatch = new HttpPatch("http://myURL");
JsonArrayBuilder Abuilder = Json.createArrayBuilder();
JsonObjectBuilder oBuilder = Json.createObjectBuilder();
for(int i=0;i<48;i++){
Abuilder.add(i+1);
}
oBuilder.add("date", "2016-09-08");
oBuilder.add("values",Abuilder);
JsonObject jo = Json.createObjectBuilder().add("puissance", Json.createObjectBuilder().add("curves",Json.createArrayBuilder().add(oBuilder))).build();
try{
//Execute and get the response.
StringEntity params =new StringEntity(jo.toString());
params.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPatch.setEntity(params);
response = httpclient.execute(httpPatch);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null) {
System.out.println(line);
result.append(line);
}
}catch(Exception e){
}
When I execute this request, I get a
"400 Error: The request has an invalid header name".
When I execute this request using Postman, this is working fine.
I am quite new at HTTP requests so do not hesitate to ask if you need more details.
StringEntity.setContentEncoding is used to set the Encoding type,
You should use StringEntity.setContentType to set the ContentType
Problem-
RestTemplate restTemplate = new RestTemplate();
restTemplate.patchForObject("http://localhost:8080/employee/1", requestBody, String.class);
Solution-
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject("http://localhost:8080/employee/1?_method=patch", requestBody, String.class);
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
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);