无法从weburl获取字符串响应?

时间:2016-02-03 09:58:05

标签: android web-services httpurlconnection

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = "";
            for (String url : urls) {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                try {
                    HttpResponse execute = client.execute(httpGet);
                    InputStream content = execute.getEntity().getContent();

                    BufferedReader buffer = new BufferedReader(
                            new InputStreamReader(content));
                    String s = "";
                    while ((s = buffer.readLine()) != null) {
                        response += s;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
           // textView.setText(Html.fromHtml(result));
            Log.i("NNNNNNNNNNNNNN", ""+Html.fromHtml(result));
        }
    }

URL:http://demo.ftheline.com/restaurant/soma-eats/app-order?order_id=710&amount=3&discount_amount=0&discount_code_id=0&restaurant_name=soma-eats&payment_method_nonce=fake-valid-visa-nonce

响应:

{
    "error": 0,
    "message": "Success",
    "url": "http://demo.ftheline.com/restaurant/soma-eats/thank-you/710"
}

如何从给定网址获取String的数据?我试过上面的代码并得到HTML错误响应?请帮忙

1 个答案:

答案 0 :(得分:0)

您可以使用以下方式将其归档。

我在我的应用程序中使用以下方式获取weburi的响应。

看看:

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {

String responseString = null;
DefaultHttpClient client = new DefaultHttpClient();
        @Override
        protected String doInBackground(String... urls) {
            String response = "";
            try {
                HttpGet httpGet = new HttpGet(url);
                HttpResponse execute = client.execute(httpGet);
                StatusLine statusLine = execute.getStatusLine();
                if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                    HttpEntity httpEntity = response.getEntity();
                    responseString = EntityUtils.toString(httpEntity);
                }else {
                    //Closes the connection.
                    execute.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(String result) {
            if(result!= null){
                // textView.setText(Html.fromHtml(result));
                Log.i("NNNNNNNNNNNNNN", ""+Html.fromHtml(result));
            }   
        }
}