gpt4 book ai didi

java - Android HttpURLConnection写入post数据

转载 作者:行者123 更新时间:2023-12-01 06:09:14 28 4
gpt4 key购买 nike

我正在尝试通过 HttpURLConnection 发送帖子数据,但它似乎没有发送帖子数据。

我能够在尝试发送 POST 请求之前立即通过 Toast 输出数据,但是当我在服务器端检查时,它会连接到 PHP 文件,但 POST 数据为空。

所以,我知道数据存在于 jsonObject 中。 我也知道它进入了 try catch 语句,但是当我连接时,它没有正确发送或接收。

try {
URL url = new URL(emailURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoOutput(true);

conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/json");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( jsonObject.toString().length() ));
conn.setUseCaches( false );

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

wr.write(jsonObject.toString());

wr.close();

BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;

// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}

String text = "";
text = sb.toString();



} catch (Exception e) {

throw new RuntimeException(e);
}

最佳答案

尝试添加方法以确保它确实连接到您的服务器。

修改您的代码,例如:

    int responseCodeFromServer = -1;
try {
responseCodeFromServer=conn.getResponseCode();
} catch (Exception e){
e.printStackTrace();
}

if (responseCodeFromServer == HttpsURLConnection.HTTP_OK){
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;

// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}

String text = "";
text = sb.toString();
}

因此,如果连接到服务器时出现问题,您将看到异常。

关于java - Android HttpURLConnection写入post数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38576335/

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