java - 在android中使用POST调用spring Controller 会导致参数为空

标签 java android spring spring-mvc servlets

我通过这个POST method发布数据或通过 first answer对于这个问题,将数据发布到配置有以下内容的 spring servlet:

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

调用 servlet 方法,但其参数“a”为空。为什么?

编辑:主要方法和AsyncTask:

主要方法

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

异步任务

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;

    }
}

最佳答案

我认为你传递了一个 json 对象,但你没有在 spring 中映射它。 在 Spring 中,您必须创建一个类,即具有名称、国家/地区、twitter 属性的 CustomClass

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

  //getters and setters should be here
} 

那么Spring中的代码应该是这样的

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

请告诉我这是否有帮助

关于java - 在android中使用POST调用spring Controller 会导致参数为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38321745/

相关文章:

java - 将 ejb 项目从 websphere 转换为 glassfish 2.0

android - 在模拟器上测试 Google map - CameraUpdateFactory 未初始化

android - 从android中应用程序的任何 Activity 打开抽屉

android - 设备语言为英文时如何加载arabic string.xml

java - 使用 junit/spring-test 运行测试用例来测试 spring WS web 服务时出现 NoInitialContextFound 异常

java - 为什么使用 spring MVC 进行对象到 json 转换在这种情况下不起作用?

java - Gradle Groovy 语法 "configurations {all*.exclude ...}"

java - Java 类型删除教程

Java:如何在不使用 throw 语句的情况下抛出自定义运行时异常?

java - 静态 block 不适用于 Spring 中的@Value