Android make DELETE web service call - java

I am playing with instagram api endpoints.
Their call sample is:
curl -X DELETE https://api.instagram.com/v1/media/{media-id}/likes?access_token=ACCESS-TOKEN
I am trying to make the call from my android app like this:
URL url = new URL(myBuiltUrl);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("DELETE");
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(false);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpsURLConnection.getOutputStream());
outputStreamWriter.write("access_token=" + token);
outputStreamWriter.flush();
String response = streamToString(httpsURLConnection.getInputStream());
The error I get while running this code is:
java.net.ProtocolException: method does not support a request body: DELETE
How can I fix my code to work correctly ?

Try putting your access_token on your URL, as you are doing with your curl command, and getting rid of the outputStreamWriter stuff.

Related

Java make HTTP call to AWS

I have set up in AWS a private API gateway, I can call it use curl like this to access it:
curl -v https://vpce-02e21f9af4f10cf2a-6y6qzepe-ap-southeast-2b.execute-api.ap-southeast-2.vpce.amazonaws.com/Test/uppercase/zzzddd -H'Host:515btqa443.execute-api.ap-southeast-2.amazonaws.com'
I can also use Postman by set the URL and set the header.
However, I seem to have an issue accessing it from Java, I think it is not adding the Header and I get 403 forbidden message.
String urlstr = "https://vpce-02e21f9af4f10cf2a-6y6qzepe-ap-
southeast-2b.execute-api.ap-southeast-
2.vpce.amazonaws.com/Test/uppercase/zzzddd";
URL url = new URL(urlstr);
HttpURLConnection con = (HttpURLConnection)
url.openConnection();
con.setRequestMethod("GET");
con.addRequestProperty("Host", "515btqa443.execute-api.ap-southeast-2.amazonaws.com");
int responseCode = con.getResponseCode();
Any ideas if i am doing something wrong in the Java ?

HttpUrlConnection method is always GET on android

URL url = new URL("http://myserver.com/myendpoint");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//connection.setRequestMethod("POST") <- this didn't help either
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("string=test");
out.close();
connection.close()
The code above WORKS on desktop JVM, sends a post request, parsed on server-side successfully with response 200, however on android, the request method stays GET (yes I checked it IS false) and results in a 404 exception. Official docs say that setting doOutput to true triggers setting the request method to POST but that doesn't seem the case.
404 is not an exception. It is a HTTP status code returned by the server you make the request to and it means that the url you make the request to is not found. That has nothing to do with POST being set or not.
Things to check:
If the url you are making a request to is right.
If the server has a POST controller/handler mapped to the url you are making the request to.
Ask the guy who develops the server if he is handling the cases right ans if he's sending the correct response codes for the relevant scenarios.
Extra info: if the url is registered on the service but a POST request is not allowed you would get a 415 response code.
When posting data to a server, I'm setting some additional request header:
String query = "string=test";
URL url = new URL("http://myserver.com/myendpoint");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
connection.setFixedLengthStreamingMode(query.getBytes("UTF-8").length);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(query);
But as suggested, the 404 exception usually means, that the endpoint, you're trying to access, isn't available.
Try it:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");

How to make REST API calls that have filter added

I am new to REST API and I want to make a REST API call which returns a JSON object
http://smlookup.dev/sec/products?search={"ABC.CP":"123A5"} - Runs fine in a browser and gives a JSON object
how do i get '?search={"ABC.CP":"12345"}' this expression to work as it filter the records
Code i am using is
String serverUrl="http://smlookup.dev/sec/products?search=";
String search=URLEncoder.encode("={\"ABC.CP\":\"12345\"}");
URL url = new URL(serverUrl+search);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("GET");
OutputStream out = httpCon.getOutputStream();
//FAILS GIVING 405 STATUS CODE
int responseCode = httpCon.getResponseCode();
All help or suggestions are helpful
Thanks!
Not sure if its normal but you dont send any data in your POST.
Furthermore you should urlencode your url, the inverted comma are not accepted like that.
URLEncoder.encode("={\"Xref.CP\":\"XAW3123A5\"}");

Google Docs API returns a 503 Service Unavailable when uploading a file. Has something changed?

I have applications that make use of the Google Docs API. Up until recently, uploads using the HTTP endpoints has been working fine. Recently, uploading has suddenly started erroring. The first call to create a session (which returns the resumable URL) works fine, and returns a resumable URL. Attempting to then send the file contents to the resumable URL throws a 503.
The relevant part of the code throwing the error is this:
URL url = new URL(resumableFileUploadUrl);
conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("client_id", OAuth2Client.CLIENT_ID);
conn.addRequestProperty("client_secret", OAuth2Client.CLIENT_SECRET);
conn.setRequestProperty("Authorization", "OAuth " + GetAuthToken());
conn.setRequestProperty("X-Upload-Content-Length", String.valueOf(fileContents.length())); //back to 0
conn.setRequestProperty("X-Upload-Content-Type", "text/xml");
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length()));
conn.setRequestProperty("Slug", fileName);
if(isUpdate)
{
conn.setRequestProperty("If-Match", "*");
conn.setRequestMethod("PUT");
}
else
{
conn.setRequestMethod("POST");
}
conn.setRequestProperty("GData-Version", "3.0");
conn.setRequestProperty("User-Agent", "GPSLogger for Android");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
wr.writeBytes(fileContents);
wr.flush();
wr.close();
int code = conn.getResponseCode();
newLocation = conn.getHeaderField("location");
The above code is used both for creating the session to get the resumable URL as well as posting file contents to the resumable URL.
Which is part of this Android activity. I am including a link to the original activity as it would probably be quite easy to reproduce the problem by simply cloning the repository. The code has remained untouched for a year.
Has something changed recently that would cause this?
I would like to avoid having to use Google Drive's APIs for now as I have not changed any code and the same code is being used in a few of my other applications in the field.
One of the most annoying “features” is the undocumented rate limit when requesting images, each request of which must be authenticated. The rate limit appears to be around 10/s.
You may be using Google API v2 which is deprecated as of now. Read the below post:
https://developers.google.com/google-apps/documents-list/terms

java : html request return error 400 on android 2.x and not 4.x

I'm trying to get an xml file from a distant server.
The server asks a username and password.
My code works fine on Android 4.x but on Android 2.x i get an Error 400.
400 Bad Request
Your browser sent a request that this server could not understand.
here is my code :
URL url = new URL("http://username:password#xx.xx.xx.xx:80/pathToXML/file.xml");
URLConnection uc = url.openConnection();
String val = (new StringBuffer("username").append(":").append("password")).toString();
byte[] base = val.getBytes();
String authorizationString = "Basic " + new String(Base64.encode(base, Base64.DEFAULT));
uc.setRequestProperty("Authorization", authorizationString);
uc.connect();
InputStream ins = uc.getInputStream(); // it fails on this line
I tried many things (adding Content-Length, SetRequestMethod to POST, set user-Agent) but it doesn't work.
If someone has any idea i'm open to it.
Thanks a lot for your help.
Cheers

Categories