我正在尝试使用Java中的HttpURLConnection
使用JSON数据发出PUT请求。我这样做的方式不起作用。我没有错误,所以我不知道问题是什么。
public static void main(String[] args) {
URL url;
try {
url = new URL("http://fltspc.itu.dk/widget/515318fe17450f312b00153d/");
HttpURLConnection hurl = (HttpURLConnection) url.openConnection();
hurl.setRequestMethod("PUT");
hurl.setDoOutput(true);
hurl.setRequestProperty("Content-Type", "application/json");
hurl.setRequestProperty("Accept", "application/json");
String payload = "{'pos':{'left':45,'top':45}}";
OutputStreamWriter osw = new OutputStreamWriter(hurl.getOutputStream());
osw.write(payload);
osw.flush();
osw.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
以下是我实际要做的请求:
我已经在同一个应用程序中对资源发出GET请求,但它运行正常。我将非常感谢有关如何调试的所有提示或如何尝试以其他方式执行此操作。到目前为止,我只尝试使用OutputStream
代替OutputStreamWriter
,但它既不起作用也不起作用。
答案 0 :(得分:25)
HttpURLConnection的Sun(Oracle)实现会缓存帖子的内容,除非您告诉它处于流模式。如果您开始与响应进行交互,则会发送内容,例如:
hurl.getResponseCode();
另外,根据RFC 4627,您不能在json中使用单引号(尽管有些实现似乎并不在意)。
因此,将您的有效负载更改为:
String payload = "{\"pos\":{\"left\":45,\"top\":45}}";
此示例适用于我
public class HttpPut {
public static void main(String[] args) throws Exception {
Random random = new Random();
URL url = new URL("http://fltspc.itu.dk/widget/515318fe17450f312b00153d/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(String.format("{\"pos\":{\"left\":%1$d,\"top\":%2$d}}", random.nextInt(30), random.nextInt(20)));
osw.flush();
osw.close();
System.err.println(connection.getResponseCode());
}
}