calling asp webservice not working as i need - java

I'm trying to send user and pass to asp webservice , but when getting back response get like this :
so how to fix it and get true of false
this is webservice link i have used :
http://ictfox.com/demo/Hafil_Updates/Login_Check.aspx?UserLogin=Demo&Password=Demo
02-20 19:57:23.326: D/Http Response:(4007): True<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body> <form name="form1" method="post" action="Login_Check.aspx?UserLogin=Demo&Password=Demo" id="form1"><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZD/N053U40olll80mNvY/Qt2aBEc" /> <div> </div> </form></body></html>
this is my full class in asyncTask android :
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://ictfox.com/demo/Hafil_Updates/Login_Check.aspx?UserLogin=Demo&Password=Demo");
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("UserLogin", "Demo"));
nameValuePair.add(new BasicNameValuePair("Password",
"Demo"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
response.getEntity().getContentLength();
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
Log.d("Http Response:", sb.toString());

Is that webservice from you or a 3dr party? It seems that it not only returns the actual return value, but also some hidden HTML stuff. Check if there is an option to call the service in a way that it returns only the desired value or even better JSON. If not, just check if the return String starts with "True"
boolean success = sb.toString().toLowerCase().startsWith("true");

You would need to modify the response sent by the server, that would be the easiest thing to do. I see that you server returns True followed by some HTML code. Make your server remove the HTML
If you don't want to modify the server side code, just look in your response for the substring True.
Additionally, to get the response I use this, which may be simpler:
httpresponse = httpclient.execute(httppost);
response = EntityUtils.toString(httpresponse.getEntity());

Related

Java HttpClient error

When I try to send a POST request with an HttpClient to a website which uses CloudFlare, I don't get the website page content.
It looks like I get "blocked" from CloudFlare.
How can I get a solution?
This is the code I use:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://website/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
First check and make sure you are sending required parameters in your request and try adding user agent in your request :
params.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0");
If you really want to check which parameters are being sent in request when you are doing it from browser, one way I know is to use Firefox extension Tamper Data. It will show you all parameters of header and post data and will allow you to modify them also.
check your server not blocked post requests in (CORS) by default

HttpGet getting text with unwanted characters

I have this in my MainActivity.java file:
public static void getLatestVersion() {
try {
String myUri = "http://www.stonequest.de/version.php";
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(myUri);
HttpResponse response = httpClient.execute(get);
String Latest = EntityUtils.toString(response.getEntity());
System.out.println(Latest);
} catch (Exception e) {
e.printStackTrace();
}
}
It gets the text, but it also adds some special characters at the beginning of the text.
This is what I get:
0.1.572
I wish to retrieve the version without any characters as shown by going to the endpoint http://www.stonequest.de/version.php
0.1.572
So how can I fix it?
Querying this URL with Firefox, I can see the same characters in the response body (with Firebug). You should mention the characterset in the toString() method, and use the same as on the server side. Preferably set both to "UTF-8".

Accessing a login api using http get method in android

I am developing an android app which uses a login api, which will allow its web users to login with their same credentials on the android device.....
the url for the api is
https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user=ecoachguest&pass=ecoachguest
which retuns a response in json
JSON object: {
status: <success or error>,
msg: <response message>,
profile: <user profile object>
}
I tried this code which I found searching on the internet but it isn't working,
private void doLogin(View view) {
//ALERT MESSAGE
_spinner.setVisibility(View.VISIBLE);
Toast.makeText(mContext, "connecting to server.... ",
Toast.LENGTH_SHORT).show();
// URLEncode user defined data
String usernameValue = username.getText().toString();
String passValue = password.getText().toString();
// Create http cliient object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+usernameValue+"&pass="+passValue;
Log.i("httpget", URL);
try
{
String SetServerString ;
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
System.out.println(usernameValue);
System.out.println(passValue);
// Show response on activity
Toast.makeText(getBaseContext(),SetServerString,Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getBaseContext(),"Fail",Toast.LENGTH_LONG).show();
_spinner.setVisibility(View.INVISIBLE);
}
}
will appreciate the help or the positive direction thanks :)
Change your code to get the HttpResponse like below,
String responseBody = "";
HttpResponse response = client.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
Log.i("GET Response Code ",responseCode + "");
switch(responseCode) {
// Means server is responding
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
// Now you can try printing your returned string here, before you go for JSON parsing
}
break;
// Add more case statements to handle other scenarios
}
The code is simple, but if still unable to understand, don't hesitate to ask.

How to send a request (and receive it) in XML format from some web-service?

I'm working in a E-Commerce website, with JSF 2.
In order to communicate with the company that makes all the operation with the banks, I need to send this XML to them (it's just a sample provided from them):
<?xml version="1.0" encoding="ISO-8859-1"?>
<requisicao-transacao versao="1.2.0" id="6560a94c-663b-4aec-9a45-e45f278e00b4" xmlns="http://ecommerce.cbmp.com.br">
<dados-ec>
<numero>1001734898</numero>
<chave>e84827130b9837473681c2787007da5914d6359947015a5cdb2b8843db0fa832</chave>
</dados-ec>
<dados-pedido>
<numero>1603662828</numero>
<valor>100</valor>
<moeda>986</moeda>
<data-hora>2010-07-14T15:50:11</data-hora>
<idioma>PT</idioma>
</dados-pedido>
<forma-pagamento>
<bandeira>visa</bandeira>
<produto>A</produto>
<parcelas>1</parcelas>
</forma-pagamento>
<url-retorno>https://www.dummyurl.du/dummypage.do?id=trhjgnerifvnidjfnvmd</url-retorno>
<autorizar>1</autorizar>
<capturar>true</capturar>
</requisicao-transacao>
So after reading a lot about how to send and XML and receive it, I create this method:
public String rent(){
//String folderAndFile = createTransaction();
//creating the HTTP Post
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://qasecommerce.cielo.com.br/servicos/ecommwsec.do");
try {
//Reading the file as an entity
FileEntity entity = new FileEntity(new File("/home/valter.silva/sample.xml"));
entity.setContentType("text/xml");
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
But the output is always :
INFO: <?xml version="1.0" encoding="ISO-8859-1"?> <erro xmlns="http://ecommerce.cbmp.com.br"> <codigo>001</codigo> <mensagem>Requisição inválida</mensagem> </erro>
Which means that my .xml that I'm sending is invalid. That for some reason, the XML is wrong.. but what ?
Is alright the way that I'm sending the file ? What can I do about it ?
update
I was trying another approach but still the output is always the same, ..., is something wrong with my code ?
//approach v1
public String rent(){
//String folderAndFile = createTransaction();
try {
File file = new File("/home/valter.silva/test.xml");
HttpPost post = new HttpPost("https://qasecommerce.cielo.com.br/servicos/ecommwsec.do");
post.setEntity(new InputStreamEntity(new FileInputStream(file),file.length()));
post.setHeader("Content-type", "text/xml; charset=ISO-8859-1");
//creating the HTTP Post
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//approach v2
public String rent(){
//String folderAndFile = createTransaction();
try {
File file = new File("/home/valter.silva/test.xml");
HttpPost post = new HttpPost("https://qasecommerce.cielo.com.br/servicos/ecommwsec.do");
//creating the HTTP Post
DefaultHttpClient client = new DefaultHttpClient();
String fileInString = fileToString("/home/valter.silva/test.xml");
InputStream inputStream=new ByteArrayInputStream(fileInString.getBytes());//init your own inputstream
InputStreamEntity inputStreamEntity=new InputStreamEntity(inputStream,fileInString.length());
post.setEntity(inputStreamEntity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Can you check that the url where you trying to post can handle your xml correctly ?
I have tried to upload the xml you provided using just simple http post to the specified url and got
<?xml version="1.0" encoding="ISO-8859-1"?> <erro xmlns="http://ecommerce.cbmp.com.br"> <codigo>001</codigo> <mensagem>Requisição inválida</mensagem> </erro>
I prefer you first try to upload the xml from outside and then try with your code .
For example i used RESTClient of Mozilla addon .

Open WebView with result from Http post

I having an issue from my HTTP Post.
The code I'm using are working (have tested to post data to a guestbook form and it worked).
Now what I want. I have created two EditText forms, that holds values. I have a submit button there I post this data (like the test I wrote about before), but now I want to post it into a login.php page (that in a normal browser redirects me to the member.php page).
Although I know the forms are correctly filled in and it successfully posted on the "test" site, I wanna get the response from login.php and check if the user is successfully logged in or if it failed, if succeeded -> redirect me to member.php page.
All I know is this:
HttpResponse response = httpclient.execute(httppost);
that executes the command. But how should I achieve the login check? Any further use of the response variable?
Well... your approach is not good at all. If you are going to allow user authenticate through your app, why do you want to redirect the user to a member.php page? why don't you just put the login form in a login.php file on the server and make the user browse through your site?
As user, if an app allows me to authenticate using EditTexts inside UI, I would expect to access all the content through the app instead of being redirected to a web interface.
Anyway, if you decide to continue doing it that way keep in mind that you would have to parse and process cookies manually, and inject them into the WebView (Google about the CookieManager class). That's the way how the user will really be logged-in in your web app.
Can you provide a small example of how to set it up? The stream I will get, is that a special server response for example, a successfully login?
Here you have:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result; // here is a string of the result!!!
}
}
} catch (Exception e) {}
return null; // if it gets here, something wrong happens with the connection
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
How do you use it? Something like this:
String result = getPostRequest("http://yourpage.com/login.php", "the username", "his/her pass");
if( result.equals("OK") ){
// voila!
}
I'm here supposing that you have something like this in your PHP code:
<?php
// login logic here
if( $success ){
die("OK");
}
?>

Categories