I'm trying to call to my API sending a JSON to delete a product from my DB; however, it doesn't delete anything.
The response of the JSON is "true," and it doesn't give to me any error; even so, when I make a query on my DB, the product is still there.
I've created a class called HttpDeleteWithBody that looks like:
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
public String getMethod() { return METHOD_NAME; }
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() { super(); }
}
And then on my doInBackGround of my Fragment, I do this:
boolean resul = true;
try {
JSONObject usuari = new JSONObject();
try {
usuari.put("idProducte", params[0]);
usuari.put("idusuari", params[1]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpEntity entity = new StringEntity(usuari.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpDeleteWithBody httpDeleteWithBody = new HttpDeleteWithBody(getResources().getString(R.string.IPAPI) + "produsuaris/produsuari");
httpDeleteWithBody.setEntity(entity);
HttpResponse response = httpClient.execute(httpDeleteWithBody);
Log.d("Response ---------->", response.getStatusLine().toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
return resul;
Furthermore, I've tried to do this:
HttpDeleteWithBody delete = new HttpDeleteWithBody(getResources().getString(R.string.IPAPI) + "produsuaris/produsuari");
StringEntity se = new StringEntity(usuari.toString(), HTTP.UTF_8);
se.setContentType("application/json");
delete.setEntity(se);
however, it doesn't work... the log says:
D/Response ---------->﹕ HTTP/1.1 200 OK
This is how I call the method:
JSONObject deleteproduct = new JSONObject();
try {
deleteproduct.put("idProducte", String.valueOf(IDPROD));
deleteproduct.put("idusuari", String.valueOf(IDUSU));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Json test per afegir prod --> ", deleteproduct.toString());
TareaWSInsertar tarea = new TareaWSInsertar();
tarea.execute(String.valueOf(IDPROD), String.valueOf(IDUSU));
I've added on my Google Chrome a plug-in called "PostMan" and when I try to do this by this way, it's deleting correctly...
What I'm doing wrong?
EDIT
I tried to use cURL, and this is the result:
It is returning me false, when I put the same JSON as PostMan; nevertheless, if I put the same JSON on PostMan, it works fine.
EDIT 2
I implemented ion library and I did it like :
JSONObject usuari = new JSONObject();
try {
usuari.put("idProducte", params[0]);
usuari.put("idusuari", params[1]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String url = getResources().getString(R.string.IPAPI) + "produsuaris/produsuari";
Log.d("CURL", "curl -X DELETE -d '" + usuari.toString() + "' " + url);
Builders.Any.F builder = Ion.with(getActivity().getApplicationContext())
.load(HttpDelete.METHOD_NAME, url)
.setTimeout(15000).setStringBody(usuari.toString());
String response = builder.toString();
Log.d("TEST", "Req response -->" + response);
}
catch (Exception ex){
resul = false;
}
And it still returning that it's OK, and don't delete anything.
This appears to be a server side issue, to be sure of this, do the following:
1) Add Ion as an dependency in your grandle.
compile 'com.koushikdutta.ion:ion:+'
2) Use the following snippen to perform your request:
JSONObject jsonObject = new JSONObject();
try{
for(BasicNameValuePair aNameValue : getParameters()){
jsonObject.put(aNameValue.getName(), aNameValue.getValue());
Log.d("TEST","parameter "+aNameValue.getName()+": "+aNameValue.getValue());
}
jsonObject.put("time_zone", Util.timeZone());
Log.d("TEST","parameter time_zone:"+Util.timeZone());
}catch(Exception e){
//
}
Log.d("CURL", "curl -X DELETE -d '"+jsonObject.toString()+"' "+getUrl());
Builders.Any.F builder = Ion.with(getContext())
.load(HttpDelete.METHOD_NAME, getUrl())
.setTimeout(BuildConfig.HttpClientMaxTimeout).setStringBody(jsonObject.toString());
String response = builder.asString().get();
Util.checkThreadUiException();
Log.d("TEST","-->"+ response);
There's no much rocket science, this is the code that I used in an app, in that method I received the parameters to send as a json, as a BasicNameValuePair collection. You can change that and directly set your json. I'm 100% porcent sure that this request will fail, because this is a server side issue.
UPDATE
JSONObject usuari = new JSONObject();
try {
usuari.put("idProducte", params[0]);
usuari.put("idusuari", params[1]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String url = getResources().getString(R.string.IPAPI) + "produsuaris/produsuari";
Log.d("CURL", "curl -X DELETE -d '"+usuari.toString()+"' "+url);
Builders.Any.F builder = Ion.with(getContext())
.load(HttpDelete.METHOD_NAME, url)
.setTimeout(BuildConfig.HttpClientMaxTimeout).setStringBody(usuari.toString());
String response = builder.asString().get();
Log.d("TEST","Req response -->"+ response)
UPDATE
Try this, perform this request through curl and let me know the result:
curl --http1.0 -X DELETE -d '{"idusuari":121,"idProducte":15}' 192.168.1.46/ServicioWebRest/api/produsuaris/produsuari
Doing this you're telling to curl to send the request through http 1.0, chunked responses are only supported by http 1.1, if there's an error in the chunk encoding, this should tell you.
Also take a look to this issue that I submitted to Ion long ago. I think that the problem that I was having that time, and your current problem are alike, maybe some of the tips there will help. Specially the part about the addHeader("Connection", "close").
Would look like this:
Builders.Any.F builder = Ion.with(getContext())
.addHeader("Connection", "close")
.load(HttpDelete.METHOD_NAME, getUrl())
.setTimeout(BuildConfig.HttpClientMaxTimeout).setStringBody(jsonObject.toString());
Finally I solved the problem, what I've done is change the HttpDelete method on my API, and instead of send a JSON, I send parameters (like a HttpGet) and now my code is like :
boolean resul = true;
HttpClient httpClient = new DefaultHttpClient();
String id____USER = params[0];
String id____PROD = params[1];
HttpDelete del =
new HttpDelete(getResources().getString(R.string.IPAPI) + "produsuaris/produsuari?idProd=" + Integer.parseInt(id____PROD)+"&idUs="+Integer.parseInt(id____USER));
del.setHeader("content-type", "application/json");
try
{
HttpResponse resp = httpClient.execute(del);
String respStr = EntityUtils.toString(resp.getEntity());
if(!respStr.equals("true"))
resul = false;
}
catch(Exception ex)
{
Log.e("ServicioRest","Error!", ex);
resul = false;
}
return resul;
This is how I call this AsyncMethod
TareaWSInsertar tarea = new TareaWSInsertar();
tarea.execute(String.valueOf(IDUSU),String.valueOf(IDPROD));
This work to me, I know it's not the best solution, but I've no much time, also I tried three solutions and noone didn't work.
Feel free to post a correct answer if you know what I was doing wrong.
When I run the following code, I get a "connection reset by peer" exception in most instances.
String rest = System.setProperty("http.keepAlive", "false");
String uri = WEB_LOG_IN + "?user_username=" + user_email
+ "&user_password=" + user_pass + "&user_mac=" + user_mac;
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri);
HttpResponse response;
String s;
try {
response = client.execute(httppost);
s = new String(EntityUtils.toByteArray(response.getEntity()),
"UTF-8");
// read json
if (s.length() > 2)
return readlogin_info(s);
else
return false;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
String rest = System.setProperty("http.keepAlive", "false");
returns null which means no "http.keepAlive" property.
I tried using httpurlconnection, but that also didn't work.
I am so confused because I think the code works without issue for some ISPs.
Based on my investigation the exception caused by Mikrotik Router latency! (Maybe! Please correct me if I am wrong!)
so I put the execute section in a while until it can get the answer from server, after multiple execution I see after 2 times of trying to connect it successfully get the answer.
int count = 0;
while (s == null) {
count++;
try {
response = client.execute(httpGet);
s = new String(
EntityUtils.toByteArray(response.getEntity()),
"UTF-8");
// read json
if (s.length() > 2)
{
return readlogin_info(s);
}
else
{
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
I'm trying to add an event in google places and the JSON returned has an invalid request in status and this endpoint has been removed in error_message. This morning it has worked correctly but now it doesn't work anymore.
I tried to use HTTP in the request to see if it returns the request denied but this doesn't do it, it always returns invalid request.
Here is my code:
private final String EVENT_URL =
"https://maps.googleapis.com/maps/api/place/event/add/json?";
private JSONObject uploadEvent() {
JSONObject jsonobj = new JSONObject();
StringEntity sEntity = null;
try {
jsonobj.put("duration", duration);
jsonobj.put("reference", reference);
jsonobj.put("summary", description);
if(url.length() > 0){
jsonobj.put("url", url);
}
sEntity = new StringEntity(jsonobj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(getUrlEvent());
httppostreq.setEntity(sEntity);
String responseText;
JSONObject JSON = null;
try {
HttpResponse httpresponse = httpclient.execute(httppostreq);
responseText = EntityUtils.toString(httpresponse.getEntity());
JSON = new JSONObject(responseText);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
private String getUrlEvent(){
//genero la solicitud como la debajo descrita
StringBuilder urlString = new StringBuilder(EVENT_URL);
urlString.append("&sensor=false&key=" + API_KEY);
return urlString.toString();
}
Can anyone helps me please?
Try
sEntity.setContentEncoding("UTF-8");
sEntity.setContentType("application/json");
httppostreq.addHeader("Content-Type", "application/json");
To quote the documentation:
Note: Events and place bumps were deprecated on September 3, 2014. The deprecation period has now ended. As of February 10th, 2015, the
API no longer accepts event or bump actions, and no longer returns
events in Place Search or Place Details responses.
I'm using the following code to post to a Google Form. If the HTTP response is not successful then the record is not marked as sent from the sqlite database and is resent during the next sync operation. The problem is I see frequent double posts because a response is not received even though the post was successful.
Is there a better way to confirm the post without creating double posts to the form?
Thanks for your help.
private Boolean performPost(String...data){
prefs = UserData.getPrefs(mContext);
spreadsheetKey = prefs.getString(UserData.PREF_SPREADSHEET_KEY,"");
ArrayList<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=" + spreadsheetKey);
int counter = 0;
for (String s : data){
results.add(new BasicNameValuePair("entry." + counter + ".single", s));
counter ++;
}
try {
post.setEntity(new UrlEncodedFormEntity(results));
} catch (UnsupportedEncodingException e) {
// Auto-generated catch block
Log.e(TAG, "An error has occurred", e);
}
try {
//client.execute(post);
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
returnCode = statusLine.getStatusCode();
Log.d(TAG, statusLine+ "\n"+ returnCode + " " + String.valueOf(post.getEntity()));
response.getEntity().consumeContent();
} catch (ClientProtocolException e) {
// Auto-generated catch block
Log.e(TAG, "client protocol exception", e);
} catch (IOException e) {
// Auto-generated catch block
Log.e(TAG, "io exception", e);
}
if (returnCode == 200){
return true;
}else{
resultTxt = SYNC_UNSUCCESSFUL_HTTP_ERROR;
Log.e(TAG,"post unsuccessful, http code :" + String.valueOf(returnCode));
sendBroadcast();
return false;
}
}
I am trying to connect to the Google Tasks by using HttpClient but always get "Unauthorised HttpResponseException".
Here is my code inside the "run" method of the AccountManagerCallback
#Override
public void run(AccountManagerFuture<Bundle> result) {
// Get the result of the operation from the AccountManagerFuture.
Bundle bundle;
try {
bundle = result.getResult();
token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Log.i("#######", token); // token does have value
String url = "https://www.googleapis.com/tasks/v1/users/#me/lists?key=" + your_api_key;
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("client_id", your_client_id);
getRequest.addHeader("client_secret", your_client_secret);
getRequest.addHeader("Authorization", "OAuth " + token);
HttpClient httpclient = new DefaultHttpClient();
String responseBody = httpclient.execute(getRequest, new BasicResponseHandler()); // exception raised here
Log.i("###", responseBody); // cannot get the response here
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using Google APIs Level 10 emulator which does have access to the internet and I did add an google account into it.
Appreciate for any helps or suggestions to make my code work. Thanks.