gpt4 book ai didi

java - 使用 HttpUrlConnection 发送数据

转载 作者:行者123 更新时间:2023-11-30 03:54:56 25 4
gpt4 key购买 nike

我正在尝试使用 HttpUrlConnection 将数据发送到 rest 服务,如下所示:

 public void makePutRequest(String objtype,String objkey,String json)
{
String uri="http://localhost:8180/GoogleMapsLoadingTest/rest/GoogleMapsErp/"+objtype+"/"+objkey;
HttpURLConnection conn=null;
URL url=null;
BufferedWriter writer=null;
try {
url=new URL(uri);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn=(HttpURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("PUT");
conn.setDoInput(true);
conn.setDoOutput(true);
System.out.println(json);
writer=new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
writer.write(json);
int rc=conn.getResponseCode();
System.out.println("The response code is "+rc);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(writer!=null)
{
try {
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(conn!=null)
conn.disconnect();
}
}

}

I get this error because the String could not be sent over

最佳答案

在获取响应代码之前,您需要对 BufferedWriter 进行 flush() 操作。

关于java - 使用 HttpUrlConnection 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23470495/

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