繁体   English   中英

使用Java从Web服务返回响应数据

[英]Return response data from a web service using java

我正在构建一个android应用程序,我需要在其中使用Web服务向其发布数据并返回字符串。 为此,我创建了一个AsyncTask来在后台执行所有操作。

protected String doInBackground(Void... params) {
            URL postUrl;
            try {
                postUrl = new URL("http://192.168.2.102/Rest%20Service/index.php");
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("invalid url");
            }

            String body = "mdxEmail=" + email + "&mdxPassword="+ password;

            byte[] bytes = body.getBytes();
            String response = null;
            HttpURLConnection conn = null;
            try {
                conn = (HttpURLConnection) postUrl.openConnection();
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setFixedLengthStreamingMode(bytes.length);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded;charset=UTF-8");
                // post the request
                OutputStream out = conn.getOutputStream();
                out.write(bytes);
                out.close();
                // handle the response
                int status = conn.getResponseCode();
                if (status != 200) {
                  throw new IOException("Post failed with error code " + status);
                } 
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return response;
        }

我的问题是如何获取从Web服务返回的数据?

发布后,您可以获取返回的数据,如下所示:

    BufferedReader in = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM