Android App and Http Requests - android

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

Related

Why my android app isn't responding after POST method?

I have a problem. I'm trying to execute POST method to my Node.js server. After POST method I'm getting all the data in server but then my app isn't responding a few seconds. Is there some bugs in my code?
My POST method:
public static void setTemp(String address, String hot, String cold) throws IOException
{
URL url = new URL(address); //in the real code, there is an ip and a port
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
try {
conn.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("hot", hot);
jsonParam.put("cold", cold);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
} catch (Exception e) {
}
finally {
conn.disconnect();
}
}
This is how I call the POST method:
private void setTemp(String hot, String cold)
{
try {
WebAPI.setTemp(Tools.RestURLPost, hot, cold);
}
catch(IOException e) {
e.printStackTrace();
}
}
And here you can find my Node.js method which I use to test successful parsing of JSON:
router.post('/post', function(req, res, next) {
console.log(req.body);
});
Without seeing the whole code it's hard to know but you're never ending the request in Node, so use: req.send/json, otherwise the Android application will wait until the request is done, which won't happen and it will timeout.
router.post('/post', function(req, res, next) {
console.log(req.body);
res.json({ success: true });
});

Delete webAPI not working for release mode apk

I have developed an android app using Web API. I'm deleting a row using HttpDelete through .NET Web API. App working perfect on debug mode. But as I published the signed release mode apk, the app gets crash on delete Web API.
Please provide me the solution for it.
Attaching code of android for delete
private class DeleteData extends AsyncTask<Integer, Void, Void> {
#Override
protected Void doInBackground(Integer... params) {
int id = params[0];
Log.d("got id",""+id);
try {
URL url = new URL("My URL");
Log.d("URL",""+url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("DELETE");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream is = httpURLConnection.getInputStream();
int byteCharacter;
String result="";
while ((byteCharacter = is.read()) != -1)
{
result += (char)byteCharacter;
}
Log.d("json api",result);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
enter image description here

Application access URL without displaying anything with Android

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();
}
}

Android- Downloading Images occasionally fails.

I am trying to download images from the net in my android application, it works most of the times but some pictures are failing to download and the Bitmap is null. The link to the images is always being there however. Any ideas what is causing this?
private class GetImage extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
int len = 500;
try {
URL url = new URL(urls[0]);
Log.v("url",urls[0]);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
int response = connection.getResponseCode();
inputstream = connection.getInputStream();
System.out.println(inputstream.toString());
bitmap = BitmapFactory.decodeStream(inputstream);
if(bitmap==null)
Log.v("Bitmap","fail");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputstream != null) {
try {
inputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "some string since it bitmap is sometimes null";
You can't always count on the network. You can use an http library like okhttp or volley that will allow you to do retries easily (or you could just retry yourself). Those libraries do a bunch of things to smooth out the http experience over using raw HttpUrlConnection.
Depending on how critical the image is, you could always hide the image in onPostExecute if it fails.

HttpGet in android .. what am I doing wrong?

I have this code from a book I have to learn about Android .. what's wrong?
I always get 01 Error Connecting which is an exception in my code while establishing http connection.
public class HttpImgActivity extends Activity {
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null; // creating My input
int response = -1;
URL url= new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection)) // if not a valid URL
throw new IOException ("NOT an Http connection");
try{
HttpURLConnection httpconn = (HttpURLConnection) conn;
httpconn.setAllowUserInteraction(false); // prevent user interaction
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect(); //initiates the connection after setting the connection properties
response = httpconn.getResponseCode(); // getting the server response
if(response == HttpURLConnection.HTTP_OK ) // if the server response is OK then we start receiving input stream
{ in = httpconn.getInputStream(); }
} // end of try
catch(Exception ex)
{
throw new IOException(" 01 Error Connecting");
}
return in; // would be null if there is a connection error
} // end of my OpenHttpConnection user defined method
*/
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap= null;
InputStream in = null;
try
{
in = getInputStreamFromUrl(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1)
{
Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
return bitmap; // this method returns the bitmap which is actually the image itself
}
ImageView img;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("http://www.egyphone.com/wp-content/uploads/2011/05/Samsung_Galaxy_S_II_2.jpg");
img =(ImageView) findViewById(R.id.myImg);
img.setImageBitmap(bitmap);
}
}
Any ideas?
It seems you catch your exception, but you don't use it for anything.
Try changing throw new IOException(" 01 Error Connecting"); to throw new IOException(ex.toString());
And you should think about using Android's logging tools, instead to see your errors through logcat:
...
catch(Exception ex)
{
Log.e("CONNECTION", ex.toString(), ex);
}
...
This makes debugging easier IMO.

Categories

Resources