I'm working on an android app that has to send and receive information from a 3rd party server. I'm not experienced at this at all, so bear with me if I give too much/too little/not the right kind of information at first.
The API that was provided to send information has the format
https://methodurl.com/username=user&password=pass&key=key&info=infotosend
When I put this URL into my desktops browser, it returns a string, which I'm also trying to get. At least, I'm assuming all it returns is a string, since if I look at the page source, there is just a string, such as "200 OK" or "401 Unauthorized".
The code I'm using is what I can glean from the web what I'm supposed to use. Unfortunately, for all I know, I'm writing code to do something very different than what I want. I've never written code to interact with a server before, so this is all new to me.
Here's my code:
TextView urlView = (TextView)findViewById(R.id.url_view);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(siteToSubmit);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
String serverResponse = client.execute(request, responseHandler);
urlView.setText(serverResponse);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Logcat in eclipse (when app is running on the emulator) is
java.net.UnknownHostException
The way I understand the code to be working is I'm creating a client that will execute on a url (like would happen when I hit enter in the URL bar on a browser), a request for that client to execute on, and a handler to receive the response from the server, which is set to be recieved as a string. I am then trying to set that string as the text in a TextView to verify that I am getting the proper response. Right now, I just get the log error, and urlView does not change. Any ideas why? Am I understanding the process correctly?
Thanks!
Add the uses-permission android.permission.INTERNET to the manifest file.
Related
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'm trying to execute a REST Post for the first time and I don't quite know where to begin.
I'm interacting with the WordPress REST API, and am trying to utilize this endpoint: /sites/$site/posts/$post_ID/replies/new, which is used to submit a new comment to a certain post.
I think I have a good grasp on working with GET requests, as I've successfully handled several of them. With those, I could say everything I needed to say to the server vis a vis the URL, but it seems there must be another step with POST requests. And my question is: What is that step(s)?
Do I wrap the content I want to submit into a JSONObject and post that? If so, how do I post it? Do I need to construct a statement somehow, similar to how I would construct a statement to execute on a database? Or is it indeed possible to pass my content along via the URL, as request parameters?
I'm aware that this question is a little on the open-ended side for SO, but I've been unable to find a good tutorial that answers these questions. If you know of one, please suggest it.
(I'm doing this all in an Android app)
My answer is taken straight from another answer on SO seen here Sending POST data in Android but ive cut and past the answer here for conveneience, Hope this helps
Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.
public void postData() {
// 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", "Hi"));
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
}
}
You need to implement a script on your server, your POST interacts with that script and inturn that script works with your database.
A typical scenario will be:
Java HTTP POST ~~~> PHP ~~~~> MySql.
A good starting point to learn PHP will be to checkout PHPAcademy tutorials on youtube.
http://www.youtube.com/course?list=EC442FA2C127377F07
PHP will as well help you encode the result in JSON and post it back to your client.
I'm new to android programming. I'm looking for a simple way to send pictures to Picasa, I looked at a lot of projects on it. I'm just looking to send a JPEG or PNG button I click, sends and displays a message that it is OK.
I know that is required a Google API and client authentication, but a lot of people show the same Intention sent.
Please help (sorry for the english: P)
I found this:
http://code.google.com/p/google-api-java-client/source/browse?repo=samples#hg/picasa-android-sample
Someone knows how to use it? But from the basics, I'm lost.
The only existing code in online for uploading photos to Picasa is this one..
Picasa Photo Uploader
Try with this one whether it can meet your requirements.If it does,then engage it with a button click event and display message on notification.finished() event to ensure that the file has been uploaded.
Quite an old post, but just for future references, I was successful in directly using http post to upload my image to Picasa. Their own Java API keeps returning errors.
I've written about this method in detail here:
File image = new File("/path/to/image.jpg");
byte[] imageContent = null;
try {
imageContent = Files.toByteArray(image);
} catch (Exception e) {
// do something
}
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://picasaweb.google.com/data/feed/api/user/default/albumid/default");
httpPost.addHeader("Authorization", "Bearer " + mAccessToken);
httpPost.addHeader("Content-Type", "image/jpeg");
httpPost.setEntity(new ByteArrayEntity(imageContent));
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
// log the response
logd(EntityUtils.toString(httpResponse.getEntity()));
} catch (IOException e){
// do something
}
This method uses Apache's HttpClient. If your Android version does not support it, you can still include this line in your Gradle file to compile it:
compile 'cz.msebera.android:httpclient:4.4.1.1'
I want to download some contacts saved on my online server and then display them in my activity. I have written a service and I am giving the code snippet from onStartCommand function, where this downloading is being done.
public int onStartCommand(Intent intent, int flags, int startId)
{
String responseStr = "";
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "get_contact"));
nameValuePairs.add(new BasicNameValuePair("uId", uId + ""));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader (new InputStreamReader(httpResponse.getEntity().getContent()));
responseStr = in.readLine();
in.close();
}
catch (ClientProtocolException e)
{
Log.e("EXCEPTION", "ClientProtocolException");
}
catch (IOException e)
{
Log.e("EXCEPTION", "IOException");
}
this.stopSelf();
return Service.START_STICKY;
}
But the problem with this code is that it takes too much time to download the data. Kindly suggest me any way to download and display this data in my activity quickly.
Thanks in advance for your help.
Well, if your server or connection is slow, there is not much you can do with your client code.
But, you should definitely consider compressing the responses from your web server and on the client code, add the header:
Accept-Encoding: gzip
There is no guarantee that you will not experience slow download or timeouts even after you enable compression at the HTTP level. At the end of the day you are dealing with unbounded data set and what works in your development environment may not work in the field with a very slow connection where a user may have 25000 contacts all with very long name.
It might be worth looking at the problem in general, considering whether you really need to load all the data right away. You may want to use some sort of pagination (see this question for example and/or use EndlessAdapter).
Try using a socket connection instead.
The thing I notice is you are not doing the download as a background task. Unless your service is running as a separate process from your main activity then this code will execute in the main application (UI) thread of the application and will negatively affect your users. I would recommend you move the code to a AsyncTask or thread launched from onStartCommand. I would then utilize a callback from the service to notify the activity that data is available to display. Also as Dmitry recommends, pagination could help you out as well for the actual download duration.
i try to build an https client for android and i need do get some request of an Servlet
but when i use the getInputStream method the applicaion hangs.
There is no error only hanging when i call the method.
String url = "https://.../Servlet";
try {
mPushLiteConnection = (HttpsURLConnection) new URL(url).openConnection();
mPushLiteConnection.setDoOutput(true);
mPushLiteConnection.setDoInput(true);
mPushLiteConnection.setRequestMethod("POST");
mPushLiteConnection.connect();
subscribe();
InputStream in = (InputStream)mPushLiteConnection.getInputStream();
unsubscribe();
mPushLiteConnection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this is only to check the call, but it didtn work.
Any idea why it hangs and tell me nothing?
the subscribe method works, when i comment out the line with the inputstream, the server show me all is correct.
I can try the same with the Firefox and it works and i can see the request.
i also put the keystore into the TrustManager.
sorry for my english i hope i explain it ennougth.
THX
I think i know the reason!
the method getInputStream() needs (why ever) the contentLength!
In the servlet i want to connect to is no contentLength couse it is an push chunked servlet... it sends all the time pieces of XML without length.
So.. HttpsURLConnection are not usefull for chunked!
Now i try the same connection with httpClient
i hope it works for it... if not: i jump behind the bus ;)
i use a different Thread
and yes i installed the certificate on the client side
i have a second connection to load a list from another servlet and it works fine, but i dont need a InputStream for it only a SAX Parser.
But i cant use the SAX Parser for this servlet, couse i dont get an XML, only XML Tags without the Start Document Tag
maybie you know how to ignore the Start Document tag? I am not sure if i need it for SAX