我正在尝试从Android到Spring MVC网络服务的简单帖子,但我得到了 对URL的发布请求导致400(错误请求):调用错误处理程序org.springframework.web.client.HttpClientErrorException:400 Bad Request
这是我的安卓代码:
protected String doInBackground(MediaType... params) {
try{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> requestEntity = new HttpEntity<Object>(postObject, headers);
RestTemplate restTemplate = new GzipJsonRestTemplate();
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, String.class);
return response.getBody().toString();
}catch(Exception exp) {
fail = true;
exp.printStackTrace();
return null;
}
}
这是我的控制人员:
// New user registration
@RequestMapping(value = "/register", method = RequestMethod.POST, headers = "Content-Type=application/json")
public @ResponseBody Response register(@RequestBody User myNewUser) {
// TODO Check if user exists
Response response;
// Create new user
userService.addUser(myNewUser);
// Set response
response = new Response();
response.setResponseCode("0");
response.setMessage("success");
response.setContent(null);
return response;
}
可能是什么问题?
答案 0 :(得分:0)
使用MY class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import com.ideal.assessmentapp_guj.utils.Applog;
public class Controller {
public static final String ERROR_UNKNOWN = "UNKNOWN_ERROR";
public static final String PARAMS_NAME = "params";
private Map<String, String> map;
private String jsonString;
private Context activity;
private AsyncTaskCompleteListener listener;
Exception exception;
private int requestCode;
private String key;
/**
*
* @param mContext
* @param map
*
* this constractor for only uploading data in background without
* showing any progress
*/
public Controller(Context mContext, Map<String, String> map,
AsyncTaskCompleteListener listener) {
if (IdealUtils.isNetworkAvailable(mContext)) {
this.map = map;
this.activity = mContext;
this.listener = listener;
AsyncHttpRequest request = new AsyncHttpRequest();
request.executeOnExecutor(AsyncHttpRequest.THREAD_POOL_EXECUTOR,
map.get("url"));
} else {
try {
if (activity != null)
Toast.makeText(
activity,
"Network Error – the application cannot connect to the internet. Please check your network connection.",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
}
public Controller(Activity con, Map<String, String> map,
AsyncTaskCompleteListener listener) {
this.map = map;
this.activity = con;
this.listener = listener;
// is Internet Connection Available...
if (IdealUtils.isNetworkAvailable(activity)) {
AsyncHttpRequest request = new AsyncHttpRequest();
request.executeOnExecutor(AsyncHttpRequest.THREAD_POOL_EXECUTOR,
map.get("url"));
// request.execute(map.get("url"));
} else {
Toast.makeText(
activity,
"Network Error – the application cannot connect to the internet. Please check your network connection.",
Toast.LENGTH_SHORT).show();
listener.onTaskCompleted(null, 0);
}
}
public Controller(Activity con, Map<String, String> map) {
this.map = map;
this.activity = con;
listener = (AsyncTaskCompleteListener) activity;
// is Internet Connection Available...
if (IdealUtils.isNetworkAvailable(activity)) {
AsyncHttpRequest request = new AsyncHttpRequest();
request.executeOnExecutor(AsyncHttpRequest.THREAD_POOL_EXECUTOR,
map.get("url"));
// request.execute(map.get("url"));
} else {
Toast.makeText(
activity,
"Network Error – the application cannot connect to the internet. Please check your network connection.",
Toast.LENGTH_SHORT).show();
listener.onTaskCompleted(null, 0);
}
}
public Controller(Activity con, Map<String, String> map, int requestID) {
this.map = map;
this.activity = con;
this.requestCode = requestID;
listener = (AsyncTaskCompleteListener) activity;
if (IdealUtils.isNetworkAvailable(activity)) {
// new AsyncHttpRequest().execute(map.get("url"));
AsyncHttpRequest request = new AsyncHttpRequest();
request.executeOnExecutor(AsyncHttpRequest.THREAD_POOL_EXECUTOR,
map.get("url"));
} else {
Toast.makeText(
activity,
"Network Error – the application cannot connect to the internet. Please check your network connection.",
Toast.LENGTH_SHORT).show();
listener.onTaskCompleted(null, requestID);
}
}
public Controller(Activity con, Map<String, String> map, int requestID,
String jsonString) {
this.map = map;
this.jsonString = jsonString;
this.activity = con;
this.requestCode = requestID;
listener = (AsyncTaskCompleteListener) activity;
if (IdealUtils.isNetworkAvailable(activity)) {
// new AsyncHttpRequest().execute(map.get("url"));
AsyncHttpRequest request = new AsyncHttpRequest();
request.executeOnExecutor(AsyncHttpRequest.THREAD_POOL_EXECUTOR,
map.get("url"));
} else {
Toast.makeText(
activity,
"Network Error – the application cannot connect to the internet. Please check your network connection.",
Toast.LENGTH_SHORT).show();
listener.onTaskCompleted(null, requestID);
}
}
public Controller(Activity con, String json, String url, int requestID) {
this.activity = con;
this.requestCode = requestID;
listener = (AsyncTaskCompleteListener) activity;
this.jsonString = json;
if (IdealUtils.isNetworkAvailable(activity)) {
new AsyncHttpRequest().execute(url);
} else {
Toast.makeText(
activity,
"Network Error – the application cannot connect to the internet. Please check your network connection.",
Toast.LENGTH_SHORT).show();
listener.onTaskCompleted(null, requestID);
}
}
class AsyncHttpRequest extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... urls) {
String params = "obj";
if (map != null) {
map.remove("url");
params = map.get(PARAMS_NAME);
map.remove(PARAMS_NAME);
if (params == null) {
params = "obj";
}
}
HttpPost httppost = new HttpPost(urls[0]);
try {
HttpClient httpclient = new DefaultHttpClient();
JSONObject jsonObject = new JSONObject();
if (map != null) {
for (String key : map.keySet()) {
System.out.println(key + " < === > " + map.get(key));
try {
jsonObject.put(key, map.put(key, map.get(key)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Applog.Log("json object", "jsonObject:" + jsonObject);
// httppost.setHeader("Content-Type", "application/json");
// httppost.setHeader("Accept", "application/json");
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-type", "application/json");
if (jsonString == null) {
// httppost.setHeader("Content-Type", "application/json");
// httppost.setHeader("Accept", "application/json");
StringEntity se;
se = new StringEntity(
"{\""
+ params
+ "\":"
+ (map != null ? jsonObject.toString()
: jsonString) + "}");
// se.setContentEncoding("UTF-8");
Applog.Log(
"Post Data",
"{\""
+ params
+ "\":"
+ (map != null ? jsonObject.toString()
: jsonString) + "}");
httppost.setEntity(se);
} else {
Applog.Log("Controller", "Send Json as object");
StringEntity se;
se = new StringEntity(jsonString);
// se.setContentEncoding("UTF-8");
Applog.Log("Post Data",
"{\"obj\":"
+ (map != null ? jsonObject.toString()
: jsonString) + "}");
httppost.setEntity(se);
}
HttpResponse response = httpclient.execute(httppost);
BufferedReader inBuffer = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String newLine = System.getProperty("line.separator");
while ((line = inBuffer.readLine()) != null) {
stringBuffer.append(line + newLine);
}
inBuffer.close();
// for (int i = 0; i < response.getAllHeaders().length; i++) {
// Applog.Log("HEADERS",
// "Response ::" + response.getAllHeaders()[i]);
// }
// Applog.Log("RESPONSE PARAMS", response.getStatusLine()
// .getStatusCode() + "");
String result = stringBuffer.toString();
// Applog.Log("Getting Result", "Result ::" + result);
return result;
// HttpResponse response = httpclient.execute(httppost);
//
// String responseBody = EntityUtils
// .toString(response.getEntity());
// return responseBody;
} catch (UnknownHostException e) {
e.printStackTrace();
exception = e;
// return ERROR_UNKNOWN;
} catch (ClientProtocolException e) {
exception = e;
e.printStackTrace();
// return ERROR_UNKNOWN;
} catch (IOException e) {
exception = e;
e.printStackTrace();
// return ERROR_UNKNOWN;
} catch (Exception e) {
exception = e;
e.printStackTrace();
// return ERROR_UNKNOWN;
}
return null;
}
@Override
protected void onPostExecute(String result) {
// if (null != pDialog && pDialog.isShowing()) {
// pDialog.dismiss();
// }
// if (result != null) {
if (listener != null) {
listener.onTaskCompleted(result, requestCode);
if (exception != null) {
listener.OnErrorFired(exception);
}
}
// }
super.onPostExecute(result);
}
}
}
如何使用
Map<String, String> map = new HashMap<String, String>();
map.put("url", Urls.API_BACK_UP);
map.put("UserID", userID + "");
map.put("ProductID", 14 + "");
map.put("DeviceID", devideID);
map.put("TableName", TABLE_NAME_RESULT_MASTER);
map.put("BackIdentity", backRestoreIdentity + "");
map.put("TableData", uploadData);
new Controller(UtilityActivity.this, map, RESULTMASTER_UPLOAD_DONE);
还有两个三个承包商。直接发送json对象使用
Map<String, String> map = new HashMap<String, String>();
map.put("url", getLoginUrl());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("UserName", username);
jsonObject.put("Password", password);
new Controller(this, map, 10, jsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
希望它有所帮助......!