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
Related
I'm using Asynctask to pass the parameters of API. The Asynctask executing but the String Response in Asynctask PostExecute giving me a null for a device with SDK 23 and below. But when the device is equal or higher to SDK24(Nougat), it works perfectly and the data are being sent to the API however when the SDK is 23 and lower data are not being sent to API. Does anyone encounter this problem? Please enlighten me what I miss in my code or I do wrong code. Massive thank you.
private class sendToServerOfficial extends AsyncTask<String,Void,String> {
int statusCodeone;
String convert_txt_et_username = et_username.getText().toString();
String convert_txt_content = et_content.getText().toString();
#Override
protected String doInBackground(String... strings) {
try {
urlURL = new URL("http://www.testingsite.com/api/sendServer?/ip="+getIPAddress+"&phone_num="+getMobilePhoneNumber+"&user_text="+convert_txt_et_username+"&content_text="+convert_txt_content);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlURL.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","UTF-8");
httpURLConnection.connect();
statusCodeone = httpURLConnection.getResponseCode();
if (statusCodeone == 200) {
InputStream it = new BufferedInputStream(httpURLConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
buff.close();
read.close();
return dta.toString();
}
}
catch (ProtocolException e) { e.printStackTrace(); }
catch (MalformedURLException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return null;
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(MainActivity.this, response + "Form is submitted already" + urlURL, Toast.LENGTH_LONG).show();
txt_inputURL.setEnabled(true);
btnClick.setClickable(true);
txt_inputURL.getText().clear();
}
}
I made an app which can tell the weather when you enter the location .. the API is taken from OpenWeatherMap.org and its displaying the weather .. i wanted to display the icon also i took the icon id and pasted in the link .. the image is not displaying..
try {
DownloadTask downloadTask = new DownloadTask();
String city = weatherInput.getText().toString();
Log.i("City name",city);
//used to encode the entered input for url.. for example San Fransisco appears in url
//as San%20Fransisco ... and to enable that we use the encoder...
String encodedCity = URLEncoder.encode(city,"UTF-8");
downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity +
"&appid=cd66504ca815ddc1971662a9f2147f84");
Log.i("Image id",icon);
ImageDownloader imageDownloader = new ImageDownloader();
myImage = imageDownloader
.execute("http://openweathermap.org/img/w/" + icon + ".png").get();
imageView.setImageBitmap(myImage);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
and here is the ImageDownloader class. icon is a global variable which i got when i parsed the API with other variables like weather conditions..
public class ImageDownloader extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
return BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Please note that i have two AsyncTask classes in a single Activity so if its causing some error .. i have no idea about it..
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.
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
After much fiddling with trying to import the libraries myself, I finally managed to find out that I can do so using the Google Plugin for Eclipse, here.
However, I seem to be unable to find any examples of how to actually use the API on Android, at least none that are compilable, as the classes required in those examples seem to not be resolvable by Eclipse, so I can only assume that these classes do not exist in the libraries that are imported by the Google Plugin for Eclipse for the URL Shortener API. The closest thing to an example I could find is here, which appears to be for Google App Engine, not Android, and uses classes that I cannot seem to get access to.
So the question is, how do I use this API to get a shortened version of a URL, in an Android application? Preferably, I would like to do it using an API Key, instead of OAuth.
First create a project on google console and enable url shortner api and get api key and the use the following Asynctask to get shortened url.
public class newShortAsync extends AsyncTask<Void,Void,String> {
String longUrl="http://stackoverflow.com/questions/18372672/how-do-i-use-the-google-url-shortener-api-on-android/20406915";
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
System.out.println("JSON RESP:" + s);
String response=s;
try {
JSONObject jsonObject=new JSONObject(response);
id=jsonObject.getString("id");
System.out.println("ID:"+id);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... params) {
BufferedReader reader;
StringBuffer buffer;
String res=null;
String json = "{\"longUrl\": \""+longUrl+"\"}";
try {
URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?key=YOUR_API_KEY");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(40000);
con.setConnectTimeout(40000);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(json);
writer.flush();
writer.close();
os.close();
int status=con.getResponseCode();
InputStream inputStream;
if(status==HttpURLConnection.HTTP_OK)
inputStream=con.getInputStream();
else
inputStream = con.getErrorStream();
reader= new BufferedReader(new InputStreamReader(inputStream));
buffer= new StringBuffer();
String line="";
while((line=reader.readLine())!=null)
{
buffer.append(line);
}
res= buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}
and then just execute this asynctask you will get a json responce in which id is present which is nothing but shortened Url.
add to your manifest in application node:
<meta-data
android:name="com.google.android.urlshortener.API_KEY"
android:value="{YOUR_API_KEY}"/>
add folowing libraries:
google-api-client-1.17.0-rc.jar
google-api-client-android-1.17.0-rc.jar
google-api-services-urlshortener-v1-rev22-1.17.0-rc.jar
google-http-client-1.17.0-rc.jar
google-http-client-android-1.17.0-rc.jar
method:
String shorten(String longUrl){
Urlshortener.Builder builder = new Urlshortener.Builder (AndroidHttp.newCompatibleTransport(), AndroidJsonFactory.getDefaultInstance(), null);
Urlshortener urlshortener = builder.build();
com.google.api.services.urlshortener.model.Url url = new Url();
url.setLongUrl(longUrl);
try {
url = urlshortener.url().insert(url).execute();
return url.getId();
} catch (IOException e) {
return null;
}
}
Now the Google shorter api needs key to work. I tried set key in manifest but it's not working. Key should be set by function library.
Urlshortener.Builder builder = new Urlshortener.Builder (AndroidHttp.newCompatibleTransport(),
AndroidJsonFactory.getDefaultInstance(), null);
Urlshortener urlshortener = builder.build();
com.google.api.services.urlshortener.model.Url url = new com.google.api.services.urlshortener.model.Url();
url.setLongUrl(longUrl);
try {
Urlshortener.Url.Insert insert=urlshortener.url().insert(url);
insert.setKey("Your API KEY");
url = insert.execute();
return url.getId();
} catch (IOException e) {
LogUtil.e(TAG, Log.getStackTraceString(e));
return null;
}
You can also use gradle apparently
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.apis:google-api-services-urlshortener:v1-rev47-1.22.0'
}
Google Shortner java gradle documentation