For example I have token variable in my android app.
I'm trying to send this variable to the server and run a query, so I'm using the following url with GET:
http://mywebsite.com/send.php?token=the_token
When user access this url, it adds the token to my database.
how I can make my android app automically access this URL on my protected void onPostExecute(String token) method?
This is what I have tried so far, but it doesn't work (don't access the URL):
protected void onPostExecute(String token) {
Toast.makeText(getApplicationContext(),"Works",Toast.LENGTH_LONG).show();
URL url;
try {
url = new URL("http://mywebsite.com/send.php?id="+token);
URLConnection urlConnection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
The toast works, and the URL is not accecced.
Another try:
protected void onPostExecute(String token) {
URL url;
Toast.makeText(getApplicationContext(),"Works",Toast.LENGTH_LONG).show();
try {
url = new URL("http://example.com/send.php?id="+token);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
#Override
protected Void doInBackground(String... params) {
String type = params[0];
String url= "http://10.0.2.2/login.php" ;
if(type.equals("Singin")) {
try {
URL Singin_url = new URL(url);
//Cannot not resolve method 'openConnection()'
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return null;
}
Why won't it let me OpenConnection ??
and i cant go forward because it says 'connection' not initialized
You need to call the openConnection() method on the URL object Singin_url. You are calling it on a String object.
#Override
protected Void doInBackground(String... params)
{
String type = params[0];
String url= "http://10.0.2.2/login.php" ;
if(type.equals("Singin"))
{
try {
URL Singin_url = new URL(url);
HttpURLConnection connection = (HttpURLConnection)Singin_url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return null;
}
Also your variable name first character should be in lower case, like signInUrl.
I'm currently using twitter fabric framework and trying to retrieve the list of my own account tweets. I tried searching online to no avail. The example in the document shows how to display a tweet based on tweetID. I do not want that. I do understand that REST client makes a http connection with the supplied variables and to retrieve the JSON results back to parse and etc.
This are my current codes which upon successful login it will display another activity which i want my tweets to be shown here.
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
token = authToken.token;
secret = authToken.secret;
Log.i("token",token);
Log.i("secret",secret);
successNewPage();
}
I have also passed the token and secret key over to the next activity using intent
public void successNewPage(){
Intent intent = new Intent(this, LoginSuccess.class);
intent.putExtra("token",token);
intent.putExtra("secret", secret);
startActivity(intent);
}
On the new activity class, i followed their documentation and came out with this,
TwitterAuthConfig authConfig = new TwitterAuthConfig("consumerKey", "consumerSecret");
Fabric.with(this, new TwitterCore(authConfig), new TweetUi());
TwitterCore.getInstance().logInGuest(new Callback() {
public void success(Result appSessionResult) {
//Do the rest API HERE
Bundle extras = getIntent().getExtras();
String bearerToken = extras.getString("token");
try {
fetchTimelineTweet(bearerToken);
} catch (IOException e) {
e.printStackTrace();
}
}
public void failure(TwitterException e) {
Toast.makeText(getApplicationContext(), "Failure =)",
Toast.LENGTH_LONG).show();
}
});
}
And the retrieve of tweets would be:
// Fetches the first tweet from a given user's timeline
private static String fetchTimelineTweet(String endPointUrl)
throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "anyApplication");
connection.setRequestProperty("Authorization", "Bearer " + endPointUrl);
connection.setUseCaches(false);
String res = readResponse(connection);
Log.i("Response", res);
return new String();
} catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
What i get in my log is:
380-380/com.example.john.fabric W/System.errīš java.io.IOException: Invalid endpoint URL specified.
Is my url wrong? Or is the token which I set in the endpointURL wrong too?
Any advice would be greatly appreciated. Thanks!
That should be the case, the message was thrown by the fetchTimelineTweet function. That should be caused by this line : URL url = new URL(endPointUrl); which tells that the endPointUrl causes MalformedURLException
EDIT :
According to the Twitter Dev Page, you should put this as endpointURL : https://dev.twitter.com/rest/reference/get/statuses/user_timeline and pass the user screenname as parameter.
EDIT 2 :
I think your code should be like this :
private static String fetchTimelineTweet(String endPointUrl, String token) // this line
throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "anyApplication");
connection.setRequestProperty("Authorization", "Bearer " + token); // this line
connection.setUseCaches(false);
String res = readResponse(connection);
Log.i("Response", res);
return new String();
} catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
I have written the below program in AsyncTask to load image from internet and show in ImageView. The program works fine if I give any direct image link, but don't work with API links.
What I mean is, for example, to have the cover of Farmer Boy from OpenLibrary, I need to give below source in html or in browser:
http://covers.openlibrary.org/b/isbn/9780385533225-S.jpg
However, if I enter above link in browser, the browser redirect to below address.
http://ia700804.us.archive.org/zipview.php?zip=/12/items/olcovers4/olcovers4-M.zip&file=49855-M.jpg
My problem is, my code works with last one, but not with the first one.
How can I get the image (in my android application) using the first link?
CODE:
private class getImageOpenLibrary extends AsyncTask<String, Void, Bitmap>
{
protected Bitmap doInBackground(String... args) {
URL newurl = null;
try {
//newurl = new URL("http://covers.openlibrary.org/b/isbn/"+args[0]+"-M.jpg"); // THIS DOES NOT WORK, args[0] = 9780064400039
newurl = new URL("http://ia700804.us.archive.org/zipview.php?zip=/12/items/olcovers4/olcovers4-M.zip&file=49855-M.jpg"); //THIS WORKS
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap mIcon_val = null;
try {
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mIcon_val;
}
//#Override
protected void onPostExecute(Bitmap result1)
{
ImageView mImageView = (ImageView) findViewById(R.id.cover);
mImageView.setImageBitmap(result1);
}
}
You should handle the redirection. The url redirects to another URL. You should open a second connection on the redirect URL. To be able to get the redirect URL, set setInstanceFollowRedirects to false on the connection and read the Location in the header fields.
URL url = new URL("http://covers.openlibrary.org/b/isbn/9780385533225-S.jpg");
HttpURLConnection firstConn = (HttpURLConnection) url.openConnection();
firstConn.setInstanceFollowRedirects(false);
URL redirectURL = new URL(firstConn.getHeaderField("Location"));
URLConnection redirectConn = redirectURL.openConnection();
Bitmap bitmap = BitmapFactory.decodeStream(redirectConn.getInputStream());
I'm currently trying to send an http request from an android app to google-app-engine, this request should be received by the server who will use the parameters passed in the URL to add a new item to the datastore.
I wrote this code:
private class AsyncConnection extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
// creating the url
URL url = new URL(params[0]);
// opening the connection
URLConnection connection;
connection = url.openConnection();
// get data about the connection
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
// connection was properly established
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream input = httpConnection.getInputStream();
return input.toString();
} else {
Log.d("CONNECTION", "connection not HTTP_OK");
}
} catch (MalformedURLException e) {
Log.d("SMARTGAN", "MalformedURLException" ,e);
} catch (IOException e) {
Log.d("SMARTGAN", "IOException" ,e);
} catch (Exception e) {
Log.d("SMARTGAN", "Exception" ,e);
} finally { }
return null;
}
}
but when I try to execute it I don't see any new item in the datastore.
The URL itself and the code on the server are fine, when I tried and sent the URL using it worked. I don't see any error message of "connection not ok" message in the log.
Mostly probably could be with hostname, have tried this solution How to make http post from android to google app engine server?
Also refer to https://developers.google.com/appengine/docs/java/tools/devserver#Command_Line_Arguments
public class UrlVarificationTask extends AsyncTask<Void, Void, Integer> {
private String url;
private UrlVarificationDelegate delegate;
private HttpURLConnection huc;
public UrlVarificationTask(String url, UrlVarificationDelegate delegate) {
this.url = url;
this.delegate = delegate;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(Void... params) {
int responseCode = 0;
try {
System.setProperty("http.keepAlive", "false");
URL u = new URL(url);
huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
responseCode = huc.getResponseCode();
} catch (MalformedURLException mal) {
responseCode = -555;
} catch (IOException io) {
responseCode = -444;
} catch (Exception ex) {
responseCode = -333;
ex.printStackTrace();
}
if (huc != null) {
try {
huc.getInputStream().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
huc.disconnect();
}
Logger.debug("Response Code==" + responseCode);
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
delegate.urlVarificationResponseCode(responseCode);
super.onPostExecute(responseCode);
}
}
I used above dode for validating url,
if HEAD give me response code 200 then only I open a url to webview.
but once I call this it keep connection and not allow any other http request even after close, what to do ?
Safe use of HttpURLConnection
huc.setRequestProperty("keep-alive", "false");
this is working as HttpURLConnection keep connection alive and hence we cann't make make further request so keep-alive setting to false resolve this problem.
For properly closing the HttpURLConnection go to the link
By this URL is closed.