java - Android 发布到休息网络服务 - 使用本地主机 glassfish

标签 java android rest post glassfish

我有一个 Android 应用程序,我需要允许用户登录。 我有登录按钮,当用户按下该按钮时,我调用 asyncTask 将用户数据发布到其余服务。我可以调用该方法,但是当我调试服务器端时,我看到参数为空,即使它作为 json 对象发送到服务器。

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 变量不为 null,它们正确获取其值

有什么想法吗?

编辑:变量值:enter image description here

最佳答案

尝试使用 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

祝你好运!

关于java - Android 发布到休息网络服务 - 使用本地主机 glassfish,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26323171/

相关文章:

java - 如果 RequestBody 中存在任何未知字段,则需要拒绝 POST/PUT 请求

android - 在终端上使用命令在 unity 上构建 APK

java - 复合主键,使用 REST 识别该资源的最佳方法是什么?

Java继承方法使用了错误的类

java - 如何正确添加jar库?

android - Amazon SimpeDB - 应用程序 - 数据保护

android - Firebase Crashlytics 在没有 Fabric API key 的情况下无法工作

带斜杠的资源的 REST 约定

wpf - 上传大型 xml 到 WCF REST 服务 -> 400 错误请求

java - 查找Java中两条路径的最长公共(public)路径