Java 在android中使用POST调用spring控制器会导致空参数
我正在通过此或向此问题发布数据,将数据发布到配置有以下内容的spring servlet:Java 在android中使用POST调用spring控制器会导致空参数,java,android,spring,spring-mvc,servlets,Java,Android,Spring,Spring Mvc,Servlets,我正在通过此或向此问题发布数据,将数据发布到配置有以下内容的spring servlet: @RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }) @ResponseStatus(HttpStatus.OK) public @ResponseBody String insert(String a) { 已调用servlet方法
@RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
@ResponseStatus(HttpStatus.OK)
public @ResponseBody String insert(String a) {
已调用servlet方法,但其参数“a”为null。为什么?
编辑:主要方法和任务:
主要方法
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;
}
}
package com.test.insert;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.net.URL;
导入java.net.urlcoder;
导入java.util.List;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.StringEntity;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONObject;
导入android.os.AsyncTask;
公共类ServerCaller扩展异步任务{
@凌驾
受保护的长doInBackground(URL…参数1){
试试{
POST(params1[0].toString());
}
捕获(例外e){
Log.realeexception(e);
抛出新的运行时异常(e);
}
返回22l;
}
私有字符串getQuery(列表参数)引发UnsupportedEncodingException{
StringBuilder结果=新建StringBuilder();
布尔值优先=真;
for(NameValuePair对:params){
如果(第一)
第一个=假;
其他的
结果。追加(&);
append(URLEncoder.encode(pair.getName(),“UTF-8”);
结果。追加(“=”);
append(URLEncoder.encode(pair.getValue(),“UTF-8”);
}
返回result.toString();
}
公共静态字符串POST(字符串url){
InputStream InputStream=null;
字符串结果=”;
试一试{
//1.创建HttpClient
HttpClient HttpClient=新的DefaultHttpClient();
//2.向给定URL发出POST请求
HttpPost HttpPost=新的HttpPost(url);
字符串json=“”;
//3.构建jsonObject
JSONObject JSONObject=新的JSONObject();
jsonObject.累加(“名称”、“a”);
jsonObject.累加(“国家”、“b”);
jsonObject.acculate(“twitter”、“c”);
//4.将JSONObject转换为JSON转换为字符串
json=jsonObject.toString();
//**在Jackson库中将Person对象转换为JSON字符串的替代方法
//ObjectMapper mapper=新的ObjectMapper();
//json=mapper.writeValueAsString(person);
//5.将json设置为StringEntity
StringEntity se=新的StringEntity(json);
//6.设置httpPost实体
httpPost.setEntity(se);
//7.设置一些标题以通知服务器内容的类型
setHeader(“接受”、“应用程序/json”);
setHeader(“内容类型”、“应用程序/json”);
//8.对给定URL执行POST请求
HttpResponse HttpResponse=httpclient.execute(httpPost);
//9.将响应作为inputStream接收
inputStream=httpResponse.getEntity().getContent();
//10.将inputstream转换为字符串
如果(inputStream!=null)
结果=convertInputStreamToString(inputStream);
其他的
结果=“不起作用!”;
}
捕获(例外e){
Log.e(e.getLocalizedMessage());
}
//11.返回结果
返回结果;
}
私有静态字符串convertInputStreamToString(InputStream InputStream)引发IOException{
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(inputStream));
字符串行=”;
字符串结果=”;
而((line=bufferedReader.readLine())!=null)
结果+=行;
inputStream.close();
返回结果;
}
}
我认为您传递了一个json对象,但在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();
让我知道这是否有帮助我认为您传递了一个json对象,但在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();
让我知道这是否有帮助是您发布了参数名
a
?是的,但我还将其命名为“dsfsadfa”-不好either@Ran共享您的post请求。它与我指定的URL完全相同。@使用此URL运行时,您正在向服务器发送数据。对吗?是否发布参数名称a
?是,但我也把它命名为“dsfsadfa”——不好either@Ran共享您的post请求。它与我指定的URL完全相同。@使用此URL运行时,您正在向服务器发送数据。对吗?很简单,但很有效!非常感谢。(我想如果我告诉你,在我想要创建一个类之前,我想检查服务器是否被称为fine…)那么简单,但是工作正常!非常感谢。(我想如果我告诉你在我想要创建一个类之前,我想检查服务器是否被称为fine,你会嘲笑我的…)