当前位置: 首页 > 知识库问答 >
问题:

Android spring mobile rest模板post请求导致400(错误请求)调用错误处理程序

龚昊然
2023-03-14

我正在尝试一个从Android到Spring MVC web服务的简单帖子,但我收到了对URL的帖子请求,结果是400(错误请求):调用错误处理程序org。springframework。网状物客户HttpClientErrorException:400错误请求

这是我的Android代码:

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

可能是什么问题?

共有1个答案

殷宇
2023-03-14

使用我的类

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

希望它能帮助。。。!

 类似资料:
  • 我正在为一个项目使用Hackerrank API。查看官方文档,点击这里! 在他们的网站上有一个使用UNIREST的例子, 由于我使用的是axios,所以我将其转换为类似的axios代码,如下所示: 我希望这只适用于示例中所示的示例,但它给我带来了以下错误: 请求失败,状态代码为400 错误:请求失败,状态代码为400 在createError(createError.js:16) 在sett(s

  • 但如果我将请求更改为“multipart/form-data”-春回错误400“bad request”: 为什么?也许我应该创造一些额外的豆子? PS:我需要“multipart/form-data”来与json对象一起发送文件。

  • 我有一个jersey服务器的例子,它适用于XML,但不适用于JSON。 如果我将此xml请求作为发送到服务器,则一切正常, 作为) 我在utilities-online.info将其翻译为JSON,并将其作为发送到相同的URL,具有相同的参数,但收到错误“400错误请求” 环境: Tomcat 7 球衣2.17 我尝试过的: 将添加到init-参数 启用init-参数为 添加了依赖项//

  • 我有一个基于Spring Web model view controller(MVC)框架的项目。Spring Web模型-视图-控制器(MVC)框架的版本是3.2.8 我有这个控制器 这个URL一切正常:

  • 目前从Angular JS controller中,我试图将JSON数据发送到后端服务。但是我有400个错误的请求错误。 在Controller中,我试图通过http服务发送数据,如下所示:

  • 我目前正在努力从API获取一些数据,但在一些请求中遇到了问题。 当前调用和其他一些类似的调用似乎不起作用,而其他调用则起作用(除了这些调用不使用“payload”参数)。我在文档中使用了相同的示例,因此不确定这些示例为什么不起作用。 回报 有人有主意吗?谢谢。