I'm attempting to use an HttpDelete object to invoke a web service's delete method. The web service's code parses JSON from the message's body. However, I'm failing to understand how to add a body to an HttpDelete object. Is there a way to do this?
With HttpPut and HttpPost, I call the setEntity method and pass in my JSON. There doesn't appear to be any such method for HttpDelete.
If there is no way to set a body for an HttpDelete object, could you please link me to a resource that uses a super class of HttpDelete such that I can set the method (delete) and set a body. I know that isn't ideal, but at this point I can't alter the web service.
Have you tried overriding HttpEntityEnclosingRequestBase as follows:
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
#NotThreadSafe
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(); }
}
That will create a HttpDelete-lookalike that has a setEntity method. I think the abstract class does almost everything for you, so that may be all that's needed.
FWIW, the code is based on this source to HttpPost that Google turned up.
Following Walter Mudnt advice, you can use this code. It works, just made it while testing my REST webservice.
try {
HttpEntity entity = new StringEntity(jsonArray.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpDeleteWithBody httpDeleteWithBody = new HttpDeleteWithBody("http://10.17.1.72:8080/contacts");
httpDeleteWithBody.setEntity(entity);
HttpResponse response = httpClient.execute(httpDeleteWithBody);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To access the response you can simply do: response.getStatusLine();
There are different interpretation in the question whether the body is allowed or not in the HTTP DELETE request. See this for example. In the HTTP 1.1 specification it is not explicitly prohibied. In my opinion you should not use body in the HTTP DELETE.
Nevertherless I think that you should use URL like mysite/myobject/objectId (shop.com/order/1234) where the objectId (a part of the url) is the additional information. As an alternative you can use URL parameters: mysite/myobject?objectName=table&color=red to send additipnal information to the server in the HTTP DELETE request. The part starting with '?' is the urlencoded parameters devided dy '&'.
If you want to send more complex information you can convert the data to JSON with respect of DataContractJsonSerializer or JavaScriptSerializer and then send the converted data (a string which I name myJsonData later) also as the parameter: mysite/myobject?objectInfo=myJsonData.
If you need to send too much additionnal data as a part of HTTP DELETE request so that you have problem with the URL length then you should probably better change the design of your application.
UPDATED: Iy you do want send some body per HTTP DELETE you can do this for example like following
// somewhere above add: using System.Net; and using System.IO;
WebClient myWebClient = new WebClient ();
// 1) version: do simple request
string t= myWebClient.UploadString ("http://www.examples.com/", "DELETE", "bla bla");
// will be send following:
//
// DELETE http://www.examples.com/ HTTP/1.1
// Host: www.examples.com
// Content-Length: 7
// Expect: 100-continue
// Connection: Keep-Alive
//
//bla bla
// 2) version do complex request
Stream stream = myWebClient.OpenWrite ("http://www.examples.com/", "DELETE");
string postData = "bla bla";
byte[] myDataAsBytes = Encoding.UTF8.GetBytes (postData);
stream.Write (myDataAsBytes, 0, myDataAsBytes.Length);
stream.Close (); // it send the data
// will be send following:
//
// DELETE http://www.examples.com/ HTTP/1.1
// Host: www.examples.com
// Content-Length: 7
// Expect: 100-continue
//
// bla bla
// 3) version
// create web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create ("http://www.examples.com/");
webRequest.Method = "DELETE";
webRequest.ServicePoint.Expect100Continue = false;
// post data
Stream requestStream = webRequest.GetRequestStream ();
StreamWriter requestWriter = new StreamWriter (requestStream);
requestWriter.Write (postData);
requestWriter.Close ();
//wait for server response
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse ();
// send following:
// DELETE http://www.examples.com/ HTTP/1.1
// Host: www.examples.com
// Content-Length: 7
// Connection: Keep-Alive
//
// bla bla
the full code could be a little more complex, but this one already will work. Nevertheless I continue to say that Web Service needed data in the body of HTTP DELETE request is bad designed.
use this,
class MyDelete extends HttpPost{
public MyDelete(String url){
super(url);
}
#Override
public String getMethod() {
return "DELETE";
}
}
in retrofit
import okhttp3.Request;
private final class ApiInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
Request oldRequest = chain.request();
Request.Builder builder = oldRequest.newBuilder();
if(condition) {
return chain.proceed(builder.build().newBuilder().delete(builder.build().body()).build());
}
return chain.proceed(builder.build());
}
}
you have to trigger condition, via something and potentially have to do some filtering for the url/header/body to remove the trigger,
unless the delete url/body/header is unique enough to not collide with post or get requests.
Related
I am asking this question based on the answers in this link
POST request via RestTemplate in JSON
I actually wanted to send JSON from client and receive the same at REST server. Since the client part is done in the link I mentioned above. For the same how would I handle that request at server end.
CLIENT:
// create request body
JSONObject request = new JSONObject();
request.put("username", name);
request.put("password", password);
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);
// send request and parse result
ResponseEntity<String> loginResponse = restTemplate
.exchange(urlString, HttpMethod.POST, entity, String.class);
if (loginResponse.getStatusCode() == HttpStatus.OK) {
JSONObject userJson = new JSONObject(loginResponse.getBody());
} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
// nono... bad credentials
}
SERVER:
#RequestMapping(method=RequestMethod.POST, value = "/login")
public ResponseEntity<String> login(#RequestBody HttpEntity<String> entity) {
JSONObject jsonObject = new JSONObject(entity.getBody());
String username = jsonObject.getString("username");
return new ResponseEntity<>(username, HttpStatus.OK);
}
This gives me 400 bad request error at client side. Hoping for some clues about how to handle this at server side.
HTTPEntity should not be used in your server method. Instead use the argument which is being passed to HTTPEntity from your client. In your case it has to String since you are passing string from client. Below code should work for you.
#RequestMapping(method=RequestMethod.POST, value = "/login")
public ResponseEntity<String> login(#RequestBody String jsonStr) {
System.out.println("jsonStr " + jsonStr);
JSONObject jsonObject = new JSONObject(jsonStr);
String username = jsonObject.getString("username");
return new ResponseEntity<String>(username, HttpStatus.OK);
}
My advice is to create bean class and use it in server and client instead of converting it to String. It will improve readability of the code.
When using the Spring RestTemplate, I usually prefer to exchange objects directly. For example:
Step 1: Declare and define a data holder class
class User {
private String username;
private String password;
... accessor methods, constructors, etc. ...
}
Step 2: Send objects of this class to the server using RestTemplate
... You have a RestTemplate instance to send data to the server ...
// You have an object to send to the server, such as:
User user = new User("user", "secret");
// Set HTTP headers for an error-free exchange with the server.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// Generate an HTTP request payload.
HttpEntity<User> request = new HttpEntity<User>(user, headers);
// Send the payload to the server.
restTemplate.exchange("[url]", [HttpMethod], request, User.class);
Step 3: Configure a ContentNegotiatingViewResolver on the server
Declare a bean of the type ContentNegotiatingViewResolver in the Spring XML or Java configuration. This will help the server automatically bind HTTP requests with bean objects.
Step 4: Receive the request on the server
#RestController
#RequestMapping("/user")
class UserAPI {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public User create(User user) {
// Process the user.
// Possibly return the same user, although anything can be returned.
return user;
}
}
The ContentNegotiatingViewResolver ensures that the incoming request gets translated into a User instance without any other intervention.
Step 5: Receive the response on the client
// Receive the response.
HttpEntity<User> response = restTemplate.exchange("[url]", [HttpMethod], request, User.class);
// Unwrap the object from the response.
user = response.getBody();
You will notice that the client and the server both use the same bean class (User). This keeps both in sync as any breaking change in the bean structure would immediately cause a compilation failure for one or both, necessitating a fix before the code is deployed.
I have a problem with creating post requests and send json with Robospice google http java client. My problem is, that the server receives an empty request data. (Nothing in postData)
#Override
public AjaxResult loadDataFromNetwork() throws Exception {
JsonHttpContent jsonHttpContent = new JsonHttpContent(new JacksonFactory(), jsonObject);
//ByteArrayContent.fromString("application/json", jsonObject.toString())
HttpRequest request = getHttpRequestFactory().buildPostRequest(
new GenericUrl(baseUrl),
jsonHttpContent);
request.getHeaders().setContentType("application/json");
request.setParser(new JacksonFactory().createJsonObjectParser());
request.setContent(jsonHttpContent);
HttpResponse httpResponse = request.execute();
AjaxResult result = httpResponse.parseAs(getResultType());
return result;
}
Thanks in advance!
You can do something like this :
public class SignIn_Request extends GoogleHttpClientSpiceRequest<Login> {
private String apiUrl;
private JSONObject mJsonObject;
public SignIn_Request(JSONObject mJsonObject) {
super(Login.class);
this.apiUrl = AppConstants.GLOBAL_API_BASE_ADDRESS + AppConstants.API_SIGN_IN;
this.mJsonObject = mJsonObject;
}
#Override
public Login loadDataFromNetwork() throws IOException {
Ln.d("Call web service " + apiUrl);
HttpRequest request = getHttpRequestFactory()//
.buildPostRequest(new GenericUrl(apiUrl), ByteArrayContent.fromString("application/json", mJsonObject.toString()));
request.setParser(new JacksonFactory().createJsonObjectParser());
return request.execute().parseAs(getResultType());
}
}
Convert your JSON into byte array and include it in your post request.
I've been hunting around for a similar solution myself and I found a decent explanation of how Google want you to format the content.
I made POJO class and just added some getters and setters and used that for the data and it seemed to work for me.
google-http-java-client json update existing object
Just as a demonstration the code will work, I am attempting to fetch some JSON data within my oncreate function. I know it should run on a different thread but I want to be sure the code successfully fetches my JSON before moving it into it's own thread.
The code is below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
/***************************************************/
final String TAG = "PostFetcher";
final String SERVER_URL = "http://kylewbanks.com/rest/posts";
// final String TAG = "PostsActivity";
// List<Post> posts;
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<JsonObject> posts = new ArrayList<JsonObject>();
Log.e(TAG, "Checking: " + posts);
// posts = Arrays.asList(gson.fromJson(reader, JsonObject[].class));
content.close();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
}
}
When I run the code, I get the second to last exception message:
Server responded with status code: 500
Can anyone please tell me what I'm doing wrong?
You are sending a HttpPost request to (obviously) an website that uses RESTful styled API.
This means, it works with HTTP Verbs (GET, POST, PUT, DELETE).
If you want to read data and the read access never changes data, use GET.
If you want to update or replace data, user PUT or POST (put usually to replace, POST to change/add). However, JavaScript does (or did) only support GET and POST requests, so keep that in mind.
If you want to delete a resource or collection, use DELETE.
That being said: If you want to load data, use Get in your case HttpGet instead of HttpPost.
Also read more about RESTful web APIs.
Edit:
In fact, calling the given URL in Fiddler2 (as stated in the comment on the other answer) results a HTML website reporting the error:
You called this URL via POST, but the URL doesn't end in a slash and
you have APPEND_SLASH set. Django can't redirect to the slash URL
while maintaining POST data. Change your form to point to
kylewbanks.com/rest/posts/ (note the trailing slash), or set
APPEND_SLASH=False in your Django settings.
Its internal server error..check if there are any exceptions are getting thrown at server side.
It has nothing to do with your android code, the problem is at server.
You can use AsyncTask to run network/filesystem related operations.
I've got a class:
public class WebReader implements IWebReader {
HttpClient client;
public WebReader() {
client = new DefaultHttpClient();
}
public WebReader(HttpClient httpClient) {
client = httpClient;
}
/**
* Reads the web resource at the specified path with the params given.
* #param path Path of the resource to be read.
* #param params Parameters needed to be transferred to the server using POST method.
* #param compression If it's needed to use compression. Default is <b>true</b>.
* #return <p>Returns the string got from the server. If there was an error downloading file,
* an empty string is returned, the information about the error is written to the log file.</p>
*/
public String readWebResource(String path, ArrayList<BasicNameValuePair> params, Boolean compression) {
HttpPost httpPost = new HttpPost(path);
String result = "";
if (compression)
httpPost.addHeader("Accept-Encoding", "gzip");
if (params.size() > 0){
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
try {
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
if (entity.getContentEncoding() != null
&& "gzip".equalsIgnoreCase(entity.getContentEncoding()
.getValue()))
result = uncompressInputStream(content);
else
result = convertStreamToString(content);
} else {
Log.e(MyApp.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private String uncompressInputStream(InputStream inputStream)
throws IOException {...}
private String convertStreamToString(InputStream is) {...}
}
I cannot find a way to test it using a standard framework. Especially, I need to simulate total internet lost from inside the test.
There are suggestions to manually turn the Internet in the emulator off while performing the test. But it seems to me as not quite a good solution, because the automatic tests should be... automatic.
I added a "client" field to the class trying to mock it from inside the test class. But implementation of the HttpClient interface seems quite complex.
The Robolectric framework allows the developers to test Http connection as far as I know. But I guess there is some way to write such a test without using so big additional framework.
So are there any short and straightforward ways of unit testing classes that use HttpClient? How did you solve this in your projects?
I added a "client" field to the class trying to mock it from inside the test class. But implementation of the HttpClient interface seems quite complex.
I am a little bit confuse about this statement. From the question title, you are asking about unit-testing httpClint, by mocking a FakeHttpClient may help you unit-testing other part of app except httpClient, but doesn't help anything for unit-testing httpClient. What you need is a FakeHttpLayer for unit-testing httpClient (no remote server, network requires, hence unit-testing).
HttpClient Dummy Test:
If you only need examine app behavior in the situation that internet is lost, then a classic Android Instrument Test is sufficient, you can programmatically turn the Internet in the emulator off while performing the test:
public void testWhenInternetOK() {
... ...
webReader.readWebResource();
// expect HTTP 200 response.
... ...
}
public void testWhenInternetLost() {
... ...
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
webReader.readWebResource();
// expect no HTTP response.
... ...
}
This requires the remote http server is completely setup and in a working state, and whenever you run your test class, a real http communication is made over network and hit on http server.
HttpClient Advanced Test:
If you want to test app behavior more precisely, for instance, you want to test a http call in you app to see if it is handle different http response properly. the Robolectric is the best choice. You can use FakeHttpLayer and mock the http request and response to whatever you like.
public void setup() {
String url = "http://...";
// First http request fired in test, mock a HTTP 200 response (ContentType: application/json)
HttpResponse response1 = new DefaultHttpResponseFactory().newHttpResponse(HttpVersion.HTTP_1_1, 200, null);
BasicHttpEntity entity1 = new BasicHttpEntity();
entity1.setContentType("application/json");
response1.setEntity(entity1);
// Second http request fired in test, mock a HTTP 404 response (ContentType: text/html)
HttpResponse response2 = new DefaultHttpResponseFactory().newHttpResponse(HttpVersion.HTTP_1_1, 404, null);
BasicHttpEntity entity2 = new BasicHttpEntity();
entity2.setContentType("text/html");
response2.setEntity(entity2);
List<HttpResponse> responses = new ArrayList<HttpResponse>();
responses.add(response1);
responses.add(response2);
Robolectric.addHttpResponseRule(new FakeHttpLayer.UriRequestMatcher("POST", url), responses);
}
public void testFoo() {
... ...
webReader.readWebResource(); // <- a call that perform a http post request to url.
// expect HTTP 200 response.
... ...
}
public void testBar() {
... ...
webReader.readWebResource(); // <- a call that perform a http post request to url.
// expect HTTP 404 response.
... ...
}
Some pros of using Robolectric are:
Purely JUnit test, no instrument test so don't need start emulator (or real device) to run the test, increase development speed.
Latest Robolectric support single line of code to enable/disable FakeHttpLayer, where you can set http request to be interpreted by FakeHttpLayer (no real http call over network), or set the http request bypass the FakeHttpLayer(perform real http call over network). Check out this SO question for more details.
If you check out the source of Robolectric, you can see it is quite complex to implement a FakeHtppLayer properly by yourself. I would recommend to use the existing test framework instead of implementing your own API.
Hope this helps.
I've been looking online for how to pass parameters to RESTlet webservice but it seem there are not much tutorial concerning RESTlet.
I would like to send some parameters gathered from a form on my android application (it would be great if i could do this using JSON).
well i solved this
as for the server side
#Post
public JSONArray serverSideFunction(Representation entity)
throws JSONException {
try {
JSONObject req = (new JsonRepresentation(entity)).getJsonObject();
System.out.println(req.getString(/* filed name */));
System.out.println(req.getString(/* filed name */));
/*
* you can retrieve all the fields here
* and make all necessary actions
*/
} catch (IOException e) {
e.printStackTrace();
}
}
as for the Android Side
HttpClient client = new DefaultHttpClient();
String responseBody;
JSONObject jsonObject = new JSONObject();
try{
HttpPost post = new HttpPost(WebService_URL);
jsonObject.put("field1", ".........");
jsonObject.put("field2", ".........");
StringEntity se = new StringEntity(jsonObject.toString());
post.setEntity(se);
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Content-type", "application/json");
Log.e("webservice request","executing");
ResponseHandler responseHandler = new BasicResponseHandler();
responseBody = client.execute(post, responseHandler);
/*
* You can work here on your responseBody
* if it's a simple String or XML/JSON response
*/
}
catch (Exception e) {
e.printStackTrace();
}
I hope this may be of help
In fact, it depends on what you want to do. With REST (see http://en.wikipedia.org/wiki/Representational_state_transfer), there are two ways to pass parameters or data. Before you need to understand some concepts:
Resource: the REST entity by itself.
Representation: corresponds to its state and can be gotten or updated using different HTTP methods. The kind of content is identified using the content type header (media type in Restlet).
Methods: the GET method is used to get the resource state, PUT to update it, POST to create a new resource and specify its state the same time, DELETE to delete a resource.
Restlet provides Java entities for REST elements.
So, after described that, you can see that passing data or parameters depends of your use case:
1°) Do you want to update the resource state? In this case, you will use the content of the request with methods like POST or PUT. The data structure is free from text, JSON, XML or binary... Restlet provides the ClientResource class to execute requests on RESTful applications. It also provides support to build the representation to send and extract data from the one received. In this case, your data gathered from a form will be used to build the representation. Here are some samples:
//Samples for POST / PUT
ClientResource cr = new ClientResource("http://...");
cr.post(new StringRepresentation("test"));
MyBean bean = new MyBean();
(...)
//Jackson is a tool for JSON format
JacksonRepresentation<MyBean> repr
= new JacksonRepresentation<MyBean>(bean);
cr.put(repr);
//Samples for GET
Representation repr1 = cr.get();
bean = (new JacksonRepresentation<MyBean>(repr1, MyBean.class)).getObject();
2°) Do you want to specify parameters on your GET requests (for example to configure data to retreive and so on)? In this case, you can simply add it on the ClientResource, as described below:
ClientResource cr = new ClientResource("http://...");
cr.getReference().addQueryParameter("q", "restlet");
Representation repr = cr.get();
In this case, your data gathered from a form will be used to build the parameters.
Hope it helps you.
Thierry
If you want request with json structure and your response as JSONObject maybe you can do like this in server side:
public class RequestJSON extends ServerRecource{
#Post("json")
public JSONObject testRequest(String entity){
JSONObject request = new JSONObject(entity);
String value1 = request.getString("key1");
int value2 = request.getInt("key2");
return /* your JSONObject response */;
}
}
And your request can be :
{"key1":"value1", "key2":value2}
I hope this can help you