【问题标题】:Send data using POST to java server from Android client and get JSON response使用 POST 从 Android 客户端向 java 服务器发送数据并获取 JSON 响应
【发布时间】:2014-02-20 04:33:27
【问题描述】:

我对 Android 编程完全陌生。我遇到了以下问题- 我想验证使用该应用程序的用户的凭据。为此,我想使用 POST 方法将登录详细信息发送到服务器。从那里我想得到 JSON 格式的响应。我不知道如何收到回复。我正在使用 Java 进行服务器端编程。

附:我稍后会处理安全问题。 以下是我的 Android 代码。我知道这是一团糟..请帮忙。

HttpURLConnection 连接; OutputStreamWriter 请求 = null;

        URL url = null;   
        String response = null;         
        String parameters = "username="+mUsername+"&password="+mPassword;   

        try
        {
            url = new URL("address");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();            
            String line = "";               
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            // Response from server after login process will be stored in response variable.                
            response = sb.toString();
            // You can perform UI operations here
            Toast.makeText(this,"Message from Server: \n"+ response, 0).show();             
            isr.close();
            reader.close();

        }
        catch(IOException e)
        {
            // Error
            return -1;
        }

【问题讨论】:

    标签: java android json jakarta-ee post


    【解决方案1】:

    有一个开源类可供您使用,您可以轻松浏览代码以了解其工作原理。实际上有很多开源库可以做到这一点,但在我看来,以下是最干净和最容易使用的库之一。

    https://github.com/kevinsawicki/http-request/blob/master/lib/src/main/java/com/github/kevinsawicki/http/HttpRequest.java

    您的代码可能看起来像这样:

    Map<String, String> params = new HashMap<String, String>();
    params.put("username", mUsername);
    params.put("password", mPassword);
    String response = HttpRequest.post(url).form(params).body();
    

    编辑

    我的原始答案(包括将参数映射到post 方法)会将请求作为 POST 发送,但 URL 中的参数。更正后的版本(form 方法)在正文中发送参数。

    【讨论】:

    • 我如何从服务器获得响应(以 JSON 形式)?非常感谢。
    【解决方案2】:

    您可以将 json 响应转换为 JSONObject 类。

    看这个应用,代码很简单。

    @Override
        public List<User> getRanking() {
                final List<User> result = new ArrayList<User>();
                String url = "http://quiz-exmo.rhcloud.com/rest/user/ranking/";
                String json = HttpUtil.doGet(url);
                try {
                        final JSONObject resultJsonObject = new JSONObject(json);
                        final JSONArray jsonArray = resultJsonObject.getJSONArray("users");
                        for (int index = 0, total = jsonArray.length(); index < total; index++) {
                                final JSONObject jsonObject = jsonArray.getJSONObject(index);
                                final User user = new User();
                                user.name = jsonObject.getString("name");
                                user.email = jsonObject.getString("email");
                                user.score = jsonObject.getInt("points");
                                result.add(user);
                        }
                } catch (JSONException e) {
                        throw new RuntimeException(e);
                }
                return result;
        }
    

    https://github.com/exmo/equizmo-android/blob/master/maven/equizmo/src/main/java/br/gov/serpro/quiz/service/rest/UserServiceRest.java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 2015-02-17
      • 2016-02-23
      • 2020-08-16
      • 1970-01-01
      相关资源
      最近更新 更多