2016-04-03 222 views
0

我从我的android应用程序发送参数到后端,并试图检索我的POST客户端在我的POST方法中发送的参数,但我仍然收到空参数,即使客户端发送非空的参数。Java REST API:POST方法获取NULL参数

的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", "[email protected]"); 
    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) { } 

相信方法的Content-Type和客户是一样的好。为什么我没有从Java后端方法接收参数?

检验:

  • 的网址是否正确,连接是否正常
  • 由应用程序发送的参数不是空
+0

在你的Java客户端中检查了'LoginResponse'吗? 使用[发贴人](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en),并将您的参数传递给相同的邮件类型的网址,让我们知道您获得了什么? 我认为在后端你不会返回任何东西 – Kathi

+0

当我发送身体数据为x-www-form-urlencoded时,我正在返回数据并且它在postman中运行良好。不知道为什么。我没有在这个问题中加入这个问题,因为它是无关紧要的。无论如何编辑它。问题是,我得到后端方法中的空参数@Kathi – Dinuka

回答

0

我们希望我得到了你,尝试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 
    } 
} 
+0

谢谢你这个工作:) – Dinuka

0

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

祝你好运