We are Borg
We are Borg

Reputation: 5313

Spring-MVC & Android: Server gets a empty JSON string from android

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"/>

Upvotes: 0

Views: 1322

Answers (1)

Javi Moll&#225;
Javi Moll&#225;

Reputation: 796

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);

Upvotes: 1

Related Questions