0

I am working on an Android project in which I want to create a RESTful POST connection to a Spring-MVC based server. I initially tried to post an object but I used to get errors. That is why I tried to send a JSON object. Currently I don't get any errors in the Android app, but when I receive the JSON object and get the String, there is nothing in the JSON object. I debugged the code to see that values are being sent correctly. I don't know what I am doing wrong. Any help would be nice. Thanks a lot.

Android code to send object :

@Override
    public void addRestaurant(Restaurant restaurant) {
        Log.d("Restaurant Name",restaurant.getRestaurantName());
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    Looper.prepare();
                    HttpClient client = new DefaultHttpClient();
                    HttpConnectionParams.setConnectionTimeout(client.getParams(),10000);
                    HttpResponse response;
                    JSONObject jsonObject = new JSONObject();

                    HttpPost post = new HttpPost(url);
                    jsonObject.put("restaurantName",restaurant.getRestaurantName());
                    jsonObject.put("postLeitZahl",restaurant.getPostLeitZahl());
                    jsonObject.put("phoneNumber",restaurant.getPhoneNumber());
                    jsonObject.put("id",restaurant.getId());

                    StringEntity stringEntity = new StringEntity(jsonObject.toString());
                    stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/JSON"));
                    post.setEntity(stringEntity);
                    response = client.execute(post);

                } catch (Exception e){
                    e.printStackTrace();
                }
                Looper.loop();
                //String response = restTemplate.postForObject(url,restaurant,String.class);
                //Log.d(response,"Response from webserver is");
            }
        });
        thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
    }
}

Spring Controller code :

    @RequestMapping(value = "/restaurant/add",method = RequestMethod.POST,consumes="application/json")
    @ResponseBody
    public String addRestaurantWebView(JsonObject restaurant){
        System.out.println(restaurant.getAsString());
        return "true";
    }

I don't know what I am doing wrong and I am having trouble finding some resources which can tell me how to configure the server according to the code in android or vice-versa. Thanks a lot ..:-)

Edit (Solution)(Partial with Java Objects)

As my original intention was to send a Java object which was failing, I reverted to JSON, but later it worked with Java, here is the Android code and the Spring-MVC Controller and bean which worked for me.

Android code :

package com.example.myapp;

import android.os.Process;
import android.util.Log;
import org.springframework.http.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class RestaurantServiceImpl  implements RestaurantService {

    String url = "http://192.168.178.40:8080/restaurant/add";

    @Override
    public void addRestaurant(Restaurant restaurant) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    RestTemplate restTemplate = new RestTemplate();
                    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity entity = new HttpEntity(restaurant,headers);
                    ResponseEntity<String> out = restTemplate.exchange(url, HttpMethod.POST,entity,String.class);
                    Log.d(out.toString(),"Response from server");
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
    }
}

Spring-MVC controller :

 @RequestMapping(value = "/restaurant/add",method = RequestMethod.POST)
    @ResponseBody
    public String addRestaurantWebView(@RequestBody Restaurant restaurant){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("restaurant", new Restaurant());
        modelAndView.addObject(restaurant);
        this.restaurantService.addRestaurant(restaurant);
        return "true";
    }

Servlet-context.xml

Add this :

<mvc:annotation-driven />

<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
               <beans:ref bean="jsonMessageConverter"/>
        </beans:property>
    </beans:bean>

    <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
6
  • First try to check the server, sending a POST manually using a rest client tool, like Advanced Rest client, or Postman. That way you will be sure if the server is working fine. Commented Feb 19, 2015 at 12:28
  • @hmartinezd : Did that. I am getting unsupported request type 415. I guess I must change the server code. Do you know how the Controller should be? Commented Feb 19, 2015 at 12:43
  • Are you setting in the Rest Client to send Json? Is your server side listening for Json? I don't have experience in what you are using on the server. Can't say for sure. Commented Feb 19, 2015 at 12:54
  • There is no such thing as setting JSON, only types of HTTP methods, I am selecting POST and sending JSON object String. Commented Feb 19, 2015 at 12:59
  • Well, there is setting to that. You can add headers. Use Content-Type and Accept headers, both set to application/json Commented Feb 19, 2015 at 15:08

1 Answer 1

1

This is how I would do: create the class Restaurant on you're Spring app. Then use it as the parameter in the request mapping with @ModelAttribute:

public String addRestaurantWebView(@ModelAttribute Restaurant restaurant) {

Then, on Android send the parameters with a MultipartEntity:

Charset charset = Charset.forName("UTF-8");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, charset);
entity.addPart("restaurantName", new StringBody(restaurant.getRestaurantName(), charset));
entity.addPart("postLeitZahl", new StringBody(restaurant.getPostLeitZahl(), charset));
entity.addPart("phoneNumber", new StringBody(restaurant.getPhoneNumber(), charset));
entity.addPart("id", new StringBody(restaurant.getId(), charset));

HttpPost post = new HttpPost(url);
post.setEntity(entity);
response = client.execute(post);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer, still the same.. Null Strings.
Thanks for your answer. Something is wrong, I have downloaded the Jar for org.apache.http.entity.mime which has MultiPartEntity, but for the 2nd attribute like restaurant.getRestaurantName() it says expected org.apache.http.entity.mine.content.ContentBody, found String. Also, charset is undefined. Can you please explain what should I do with these variables?
Ops, my bad. Edited answer
I am setting charset to Charset.defaultCharset();
Sorry, that didn't do it. Now it does not even touch the server with above code...Is it ok with you to continue this in chat?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.