gpt4 book ai didi

java - 使用 Java 的 POST 请求(AsyncTask)

转载 作者:行者123 更新时间:2023-12-01 17:54:34 24 4
gpt4 key购买 nike

我正在尝试使用 Java 发出 HTTP Post 请求,这里是代码

protected class DownloadInfoOfWeather extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {

final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
String result = "";

try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");
connection.addRequestProperty("User-Agent", USER_AGENT);
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

connection.setDoOutput(true);
DataOutputStream write = new DataOutputStream(connection.getOutputStream());

write.writeBytes(params[1]);
write.flush();
write.close();

// Response: 400
Log.e("Response", connection.getResponseCode() + "");

} catch (Exception e) {
Log.e(e.toString(), "Something with request");
}

return null;
}
}

public void clickHelloWorld (View view) {

DownloadInfoOfWeather downloadInfoOfWeather = new DownloadInfoOfWeather();

String url = "https://query.yahooapis.com/v1/public/yql";
String body = "q=\"select wind from weather.forecast where woeid=2460286\"&format=json";

downloadInfoOfWeather.execute(url, body);

}

当我运行此代码时,我得到 Response: 400;我使用雅虎 API enter image description here另一方面,使用curl一切正常enter image description here

有人知道如何解决这个问题吗?

最佳答案

如果您从字符串中删除引号,它将正常工作 - 就像那样

.execute(
"https://query.yahooapis.com/v1/public/yql",
"q=select wind from weather.forecast where woeid=2460286&format=json")

我还稍微清理了你的连接代码

protected static class DownloadInfoOfWeather extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {

try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "*/*");

connection.setDoOutput(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(params[1]);
writer.close();

connection.connect();

// Response: 400
Log.e("Response", connection.getResponseMessage() + "");

} catch (Exception e) {
Log.e(e.toString(), "Something with request");
}

return null;
}
}

关于java - 使用 Java 的 POST 请求(AsyncTask),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46328854/

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