Ran
Ran

Reputation: 662

Calling a spring controller with POST in android result in a null parameter

I am posting data by this POST method or by the first answer to this question, posting the data to a spring servlet configured with:

@RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
@ResponseStatus(HttpStatus.OK)
public @ResponseBody String insert(String a) {

The servlet-method is called, but its parameter 'a' is null. Why?

Edit: The main method and the AsyncTask:

main method

ServerCaller serverCaller = new ServerCaller();
        try {
            serverCaller.execute(new URL("http://192.168.56.1:8080/SpringHibernateExample/insert"));
        }

AsyncTask

package com.test.insert;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.os.AsyncTask;

public class ServerCaller extends AsyncTask<URL, Integer, Long> {
    @Override
    protected Long doInBackground(URL... params1) {
        try {               
            POST(params1[0].toString());
        }
        catch (Exception e) {
            Log.realException(e);
            throw new RuntimeException(e);
        }

        return 22l;
    }

    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }

    public static String POST(String url) {
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name", "a");
            jsonObject.accumulate("country", "b");
            jsonObject.accumulate("twitter", "c");

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person); 

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content   
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        }
        catch (Exception e) {
            Log.e(e.getLocalizedMessage());
        }

        // 11. return result
        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }
}

Upvotes: 0

Views: 627

Answers (1)

Periklis Douvitsas
Periklis Douvitsas

Reputation: 2491

i think you pass a json object but you do not map it in spring. In Spring you have to create a class ie CustomClass with properties name, country, twitter

public class CustomClass{
  private String name;
  private String country;
  private String twitter;

  //getters and setters should be here
} 

then the code in Spring should look like this

@RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
@ResponseStatus(HttpStatus.OK)
public @ResponseBody String insert(@RequestBody CustomClass cs) {
   cs.getName(); 

Let me know if this helped

Upvotes: 2

Related Questions