2014-10-12 56 views
0

我有一个android应用程序,我需要启用用户登录。 我有登录按钮,当用户按下按钮时,我调用一个asyncTask将用户数据发送到其余服务。我可以调用该方法,但是当我调试服务器端时,我发现参数是空的,即使它作为json对象发送到服务器。安卓系统的博客webservice - localhost glassfish

Android客户端代码:

class LoginByEmail extends AsyncTask<String,Void,String> { 

    @Override 
    protected String doInBackground(String... strings) { 

     String url = strings[0]; 
     String respStr = ""; 
     String userEmail = strings[1]; 
     String userPassword = strings[2]; 

     HttpResponse response; 
     JSONObject data = new JSONObject(); 

     try{ 

      HttpClient client = new DefaultHttpClient(); 
      HttpPost post = new HttpPost(url); 
      post.setHeader("Accept","application/json"); 
      post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF8"); 

      data.put("email",userEmail); 
      data.put("password",userPassword); 


      StringEntity se = new StringEntity(data.toString()); 
      post.setEntity(se); 

      response = client.execute(post); 
      respStr = EntityUtils.toString(response.getEntity()); 

     }catch (Exception e){ 
       respStr = e.getMessage().toString(); 
     } 
     return respStr; 
    } 
} 

服务器端代码

@Path("/emailLogin") 
@POST 
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) 
@Produces(MediaType.APPLICATION_JSON) 
public String emailLogin(@FormParam("email") String email, @FormParam("password") String password) 
{ 
    String user = sm.loginByEmail(email,password); 
    return user; 
} 

我使用的是GlassFish作为我的虚拟主机提供商并部署到我的休息web服务,该emailLogin功能是从其余的web服务。

我不明白为什么电子邮件和密码参数传输为空。

注:的USEREMAIL和userPassword的变量不为空,他们得到他们的价值正确

任何想法?

编辑:变量值:enter image description here

+0

你可以登录/打印/等JSON对象的客户端,只是为了确认这些值不为空? – Thufir 2014-10-12 08:42:10

回答

1

尝试namevaluepairs中,而不是JSONObject的,这应该工作:

List<NameValuePair> data = new ArrayList<NameValuePair>(); 
data.add(new BasicNameValuePair("email",userEmail)); 
data.add(new BasicNameValuePair("password",userPassword)); 
post.setEntity(new UrlEncodedFormEntity(data)); 

编辑:

我建议你使用这个项目作为一个图书馆。

https://github.com/matessoftwaresolutions/AndroidHttpRestService

它让您能够轻松处理的API,控制网络的问题等

你可以找到使用的样本存在。

你只需要:

构建您的网址 告诉组件在POST模式下执行 构建您的JSON

祝你好运!

+0

谢谢我会尝试。你为什么jsonObject不工作?因为它仍然想作为json转移。 +1,因为它有效:) – Elior 2014-10-12 09:10:31

+0

我将编辑我的答案,并附上我开发的组件的链接。您可以发送JSONObjects,并发出GET/PUT/POST请求,控制您的互联网连接以显示敬酒或在设备没有连接时执行任何操作等。它非常易于使用。请标记答案,因为那里是正确的,如果它真的是! :) – 2014-10-12 09:15:21