gpt4 book ai didi

java - 我的程序不会通过 HttpPost

转载 作者:行者123 更新时间:2023-11-29 23:48:27 28 4
gpt4 key购买 nike

在我的 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 "));
}
}

并且,为了在我的 Activity 中调用类,我使用 new DownloadFilesTask();。问题是,当我调试我的私有(private)类时,调试器在 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

最佳答案

使用 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了解击球手。

关于java - 我的程序不会通过 HttpPost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51156312/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com