我的程序不会通过HttpPost

时间:2018-07-03 13:50:05

标签: java android httprequest

在我的CountryActivity.java中,我有一个HttpRequest来检索维基百科的json信息。 这是我使用的AsyncTask代码:

   private class DownloadFilesTask extends AsyncTask<URL, Integer, String> {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");
    protected String doInBackground(URL... urls) {
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpEntity httpEntity = httpResponse.getEntity();
        try {
            is = httpEntity.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                System.out.println(line);
            }
            is.close();
            return sb.toString();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String result) {
        showDialog(Integer.parseInt("Downloaded "));
    }
}

而且,要在我的活动中调用班级,我使用new DownloadFilesTask();。 问题是,当我调试私有类时,调试器在行HttpPost httpPost = new HttpPost("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");中停止,甚至无法检索json。你知道会发生什么吗?我的应用程序没有崩溃或什么都没有...

这是我的日志:https://pastebin.com/EgVrjfVx

1 个答案:

答案 0 :(得分:1)

使用HttpURLConnection打开到url的连接,并将setRequestMethod()设置为GET

URL obj = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");
HttpURLConnection http = (HttpURLConnection) obj.openConnection();      
http.setRequestMethod("GET");

然后获取其输入流,并通过BufferedReader读取到您的构建。

BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
}
reader.close();
String json_string = sb.toString();           // your json data

选中here full example以了解击球手。