gpt4 book ai didi

java - 发送 HTTP POST - Android

转载 作者:太空宇宙 更新时间:2023-11-04 13:42:23 26 4
gpt4 key购买 nike

我知道有人问过这个问题,但大多数都已经过时,并且方法已被弃用。我找到了这个解决方案,

new Thread( new Runnable() {
@Override
public void run() {
try {
String query = "param=" +"item"+"&other="+"num";

URL url = new URL("http://www.url.com/url_post.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Set to POST
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(10000);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(query);
writer.flush();
writer.close();


} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.toString());
}
}
}).start();

但是,它没有提供如何获取返回的数据,例如,我返回一些 JSON,我从哪里获取返回的数据?

感谢您的帮助:)

最佳答案

这样做

 //Get Response 
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');

最后,在响应中,您将获得响应 JSON 字符串,然后执行您想做的操作。

欲了解更多详情,请访问此链接 http://www.xyzws.com/javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

关于java - 发送 HTTP POST - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130147/

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