Java REST API: POST 方法获取 NULL 参数

Java REST API: POST Method gets NULL parameters

我正在从我的 android 应用程序向后端发送参数,并试图在我的 POST 方法中检索我的 android 客户端发送的参数,但我一直收到空参数即使客户端发送的参数不为空。

Java POST 方法:

@POST
@Produces({ "application/json" })
@Path("/login")
public LoginResponse Login(@FormParam("email") String email, @FormParam("password") String password) {
    LoginResponse response = new LoginResponse();

    if(email != null && password != null && email.length() != 0 && password.length() != 0){
        //Detect if null or empty
        //Code
    }

    return response;
}

Android 客户:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY_APP_NAME.appspot.com/user/login");

String json = "";
JSONObject jsonObject = new JSONObject();

try {
    jsonObject.accumulate("email", "roger@gmail.com");
    jsonObject.accumulate("password", "123");

    json = jsonObject.toString();

    StringEntity se = new StringEntity(json);
    httppost.setEntity(se);
    httppost.setHeader("Content-Type", "application/json");
    httppost.setHeader("ACCEPT", "application/json");
    HttpResponse httpResponse = httpclient.execute(httppost);
}
catch(Exception ex) { }

我相信方法和客户端的内容类型也是一样的。为什么我没有收到来自 Java 后端方法的参数?

已检查:

我们希望我能找到你,试试NameValuePair

public void postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");

    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "123"));
        nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // Catch Protocol Exception
    } catch (IOException e) {
        // Catch IOException
    }
} 

以防万一你有类似的问题,我建议使用 Fiddler 这是一个免费的 http 检查器和调试器,您可以通过它查看您的应用发送到后端服务器的 http 请求和后端应答。

祝你好运