Here is my web service code
I can call it in my browser using http://sheltered-taiga-3258.herokuapp.com/toi/<input parameters> I am collecting Input parameters from user on android device. Obviously web service returns a JSON data which I need to display at client side in android application. I went through many posts and tutorials on android and web service but was not successful as many have the web service example of POST request and service in PHP. I want to do it for GET and service is in flask.
Please help Thank you.
EDIT:
I am calling web service using HttpGet object and I am passing my URL as parameter to it.
HttpGet httpget = new HttpGet(myURL);
and I am Constructing myURL as
EditText inputString = (EditText) findViewById(R.id.serverText);
String appendString =URLEncoder.encode(inputString.getText().toString(), "UTF-8") ;
private final HttpClient Client = new DefaultHttpClient();
String myURL = "http://sheltered-taiga-3258.herokuapp.com/toi/" + appendString;
Here I am getting myURL as
http://sheltered-taiga-3258.herokuapp.com/toi/hc+stays+toll+collection but I want it in this manner
http://sheltered-taiga-3258.herokuapp.com/toi/HC%20stays%20toll%20collection%20in%20kolhapur%20city
I know there is some url encoding problem but dont know way out of it.
Here is what gave me solution to my question may not be the suggestible and standard way of doing it but got me out of the problem:
String appendString = (inputString.getText().toString()).replace(" ", "%20") ;//here %20 is encoding for space
String myURL = "http://sheltered-taiga-3258.herokuapp.com/toi/" + appendString;
That gave me this :
http://sheltered-taiga-3258.herokuapp.com/toi/HC%20stays%20toll%20collection%20in%20kolhapur%20city
instead of this
http://sheltered-taiga-3258.herokuapp.com/toi/hc+stays+toll+collection
If I find the authentic way of doing this thing I will surely be posting it here marked as answer
Related
I'm trying to do a post request with a WebView on Android.
After searching for days and trying dozens of things i couldn't get it work. In SWIFT it's just a few lines of code so i thought there must also be a simple way to do a post request for a webview on android.
As (for 2016) EncodingUtils and HTTPClient are deprecated this are my current approaches:
String url = "http://example.com/php.php";
String postData = null;
postData = "param1=" + URLEncoder.encode("1234567890", "UTF-8");
webcontent.postUrl(url,postData.getBytes());
//or
webcontent.postUrl(url, Base64.encode(postData.getBytes(), Base64.DEFAULT));
Both just result in a blank screen. There is just one parameter to be sent and a string containing html from the server should be received.
In addition, the php on the server returns a html-string with colored background irrespective of any input, but even this isn't displayed so maybe the whole request never reaches the server?
Thanks in advance!
In Android you do not use webView to access the content of the HTTP response. You'll need to use HttpClient for that purpose!
See this nice tutorial which explains the fundamentals! Also see this video if you find it hard!
Hope it helps!
Im new to Android development but Im trying to do an application for Opencart to allow users to enter in their own store to administrate it.
Lets go to the point. In order to get the information from the store i created a page where all the information is presented in XML, so the idea is that the user login, and then redirects to this page and with the http response, parse the xml and voilá!.
I have already the xml parser, but Im having some difficulties with the http connection. Let me explain a little bit more:
Basically, to log into any store, you need to go to www.example.com/admin (I will be using my testing online address to see if someone is able to help me), in this case http://www.onlineshop.davisanchezplaza.com/admin . Once we arrive to the page we arrive to the login system. The login system uses post to send the username: admin and password:admin and redirects to http://onlineshop.davidsanchezplaza.com/admin/index.php?route=common/login and once it verify your identity, it gives you a Token (here I start having some problems). http://onlineshop.davidsanchezplaza.com/admin/index.php?route=common/home&token=8e64583e003a4eedf54aa07cb3e48150 . Well, till here, im very okay, and actually developed an app that can do till here, actually i can "hardcode" read the token from the http response it sends me (what is actually not very good).
Here comes my first question: HOW TO GET FROM THE HTTPresponse the token value? (by now, as I said, I can only get the token by reading all the response, and if we find the string token=, take what comes next ... not good).
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpPost httpPost = new HttpPost("http://onlineshop.davidsanchezplaza.com/admin/index.php?route=common/login");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", "admin"));
nameValuePairs.add(new BasicNameValuePair("password", "admin"));
try{
Log.d(DEBUG_TAG, "Try ");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8096);
Log.d(DEBUG_TAG, "br :" + br);
String line;
while ((line = br.readLine()) != null) {
Log.d(DEBUG_TAG, "br :" + line);
if(line.contains("token=")){
int index = line.indexOf("token=");
String aux = line.substring(index + "token=".length(), index + 32 + "token=".length());
token = aux; //Yes, I know, its not the best way.
break;
}
}
} catch (IOException e) {
Log.d(DEBUG_TAG, "Finally");
}
Second question, (and more important), now having the token (in the example 8e64583e003a4eedf54aa07cb3e48150), I need to go to the route android/home where is the xml information generated. (http://onlineshop.davidsanchezplaza.com/admin/index.php?route=android/home2&token=8e64583e003a4eedf54aa07cb3e48150). As I was reading, in httpget, we can either set the parameters, or directly send the url with the parameters already inside the url. Is in this step where it stops. Maybe is the internet connexion in China, maybe (most sure) im doing something wrong. Sometimes it just come the timeout connexion, others it just send me back to the login page.
Here is the code how i do (edit: I was a noob, and didnt create the httpclient to receive the answer, sorry!):
String s = "http://onlineshop.davidsanchezplaza.com/admin/index.php?route=common/home&token=";
String tot = s.concat(token);
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpGet httpget = new HttpGet(tot);
try{
Log.d(DEBUG_TAG, "Try ");
HttpResponse response = httpClient.execute(httpget);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8096);
Log.d(DEBUG_TAG, "br :" + br);
} catch (IOException e) {
Log.d(DEBUG_TAG, "Finally");
}
I dont need someone to tell me how to do it, just need a little guidance to solve the issue, I really appreciate any comment or help you can offer, or extra documentation :).
As a bonus, if someone can give me further details about how can I test the http get, I will appreciate, I only know how to write it in the web browser, and works fine.
It's a while since I last did something for Android, but here is my advice:
for the login purpose from Android application into the OpenCart administration I recommend creating a new mobile login page, e.g. instead of accessing http://yourstore.com/admin/ which redirects You to http://.../admin/index.php?route=common/login create Your own action e.g. androidLogin() within this controller (admin/controller/common/login.php and You will access it directly via http://yourstore.com/admin/index.php?route=common/login/androidLogin. Why special action? Because the default login action redirects the user (using normal browser) to the home while setting the security token into the URL within the query string part. In Your own action You won't redirect but respond with XML containing this security token so that You can easily extract that token using Your XML parser.
I cannot address second problem exactly but from what I remember I was passing a query string in different way (now I cannot find any similar solution on the internet).
Here is my 5 cents for the second question :
After playing a bit with the browser I realized :
Set Cookies
Your request to ...?route=android/home2&token= seems to be rejected if you are missing cookies. That is, you probably need to extract cookies from first server response and set them for further requests either manually (via conn.setRequestProperty("Cookie", cookie); or using Android CookieManager
User agent
Some server may reject your request just because you are missing "User-Agent" property in request header. To be safe, you could set it to something like conn.setRequestProperty("User-Agent", "Mozilla/5.0");
Extra note - I suggest that you also handle redirects correctly, as for example when you POST your admin/admin credentials you get 302 response and redirected to ...?route=common/home page
Also, you don't need to set conn.setDoInput(true) for UrlConnection while doing GET request.
Hope that helps.
I don't see any catch statement for the try in the second question, this catch may have the info you need to know what's going on.
For the first question try to convert InputStreamReader to a String, and use the String for a
url constructor, with the url (or uri i'm not sure right now, and can't test it) object try .getQueryParameter("parameter").
For your second question when i tried to login using the token that you have provided, the web page replied with invalid token. Can you login with the token that you have provided? If not, try to get a new token. Maybe the token have expired.
I create an application in which i get the response from web service .
The response is
"I might be in danger. I have triggered my panic alarm which is connected to you. Call me now. If i'm not answering, contact the police. My position is:http://maps.google.com/maps?q=21.183783,72.823548"
3.I store the string in text view.and i want to open HTTP URL in browser,on the click of text.but how can i get HTTP URL in whole string plese give me idea.
You can do this easily with php...
If you are able to run php, this should do it.
$string = $_GET['string'];
OR
$string = $_POST['string'];
this may change depending on how you get the responce from the website, feel free to send me the form which you get the responce and ill change it accordingly.
$string_chunks = explode('http://',$string,2);
$url = 'http://'.$string_chunk['1'];
Basically, this will take the string, find the "http://" and create 2 strings out of it. one with the content before the "http://" and one with the content after, which is the url. so it would return $string_chunk['0'] and $string_chunk['1']
var response = "ur response string";
var indexofHttp = response.indexOf('http://');
var url = response.substring(indexofHttp);
In my browser, or in iOS, when I try to get the contents of a URL with encoded http authentication information in the form
http://myUser:myPassword#www.example.com/secure/area/index.html
It just works. I'm getting URLs from a web service, and I'd like to avoid trying to parse them up for their HTTP auth info if I can help it. Is there a way to do something similar in Android without actually parsing the URLs? Alternatively, what is the best way to go about that?
UPDATE:
I find that when I try to set the authentication information in an Authorization header, I get a very strange FileNotFoundException.
Here's the code I'm using:
URL url = new URL(urlString);
URLConnection connection;
String authority = url.getAuthority();
if (authority.contains("#")) {
String userPasswordString = authority.split("#")[0];
url = new URL(urlString.replace(userPasswordString + "#", ""));
connection = url.openConnection();
String encoded = new String(Base64.encode(userPasswordString.getBytes(), Base64.DEFAULT), "UTF-8");
connection.setRequestProperty("Authorization", "Basic " + encoded);
} else {
connection = url.openConnection();
}
InputStream responseStream = connection.getInputStream();
All the info seems to check out, I've verified the url is correct, the base64 string is correct, and the file is certainly on the server--I have no trouble at all opening it with Firefox, and Firebug shows all the right headers, matching what I've sent as far as I can tell. What I get though is the following error (url host changed to protect the innocent):
java.io.FileNotFoundException: http://a1b.example.com/grid/uploads/profile/avatar/user1/custom-avatar.jpg
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
Any idea what this is all about?
I looked into using HttpClient, but saw that in Issue 16041 it is recommended that we prefer URLConnection.
That looks like your browser is applying some extra rules to parsing the URL. In Android you can use HTTP Client's authentication mechanism such as BASIC and DIGEST to do the same things. Which one you choose is dependent on the server you are trying to authenticate against.
Here is a good page to get you started.
Unfortunately, on Android you can't pass the user info (username/password) in that format to either java.net.URL or HttpClient and have it work like in a browser.
I'd recommend using URI (see http://download.oracle.com/javase/1.5.0/docs/api/index.html?java/net/URI.html) to do this: pass your URL to the URI constructor that takes a String and then you can extract the user info (using getUserInfo()). You can then either use HttpClient's authorization classes (see http://developer.android.com/reference/org/apache/http/auth/package-summary.html) or build the basic auth header yourself (an example is given at http://www.avajava.com/tutorials/lessons/how-do-i-connect-to-a-url-using-basic-authentication.html).
I want to build an application which takes user/pass information from user and use it on an https webpage and extract the returned raw html code from that page.
I want to know is this possible?
If so, what sort of class i should use. Can it be done with some hidden webview mechanism. Sine i think we can access the java script variable in a webview from our application. So is this possible. Or i am just wasting my time in this direction.
If you are asking if it is possible to 'download' a webpage without actually displaying it in a WebView then try this...
HttpClient client=new DefaultHttpClient();
HttpGet getMethod = new HttpGet(Url);
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String response = client.execute(getMethod, responseHandler);
EDIT: Sorry - the Url parameter passed to HttpGet() above is actually a String variable containing a url to the wep page you want.
Pretty old subject here, but I see that I'm not the only one facing this situation.
This is how I understand it:
HttpClient objects and WebView objects will not share the same "session" scope through your application.
That is, if you have this URL that performs authentication and starts a valid session on a website; and following that, you try to open one of those website pages - session protected - through the webview, the webview will act as if no session were available. WebView is not aware of the HttpClient session.
A solution to that is to call the URL that starts a session through the WebView.postUrl method like this:
webView.postUrl(url, EncodingUtils.getBytes(postParameters, "BASE64"));
I'm sure this can be done in a hidden webView.