我试图通过json
发布HttpUrlConnection
请求(请注意,我只需将数据推送到服务器,响应将被忽略)。我已经完成了一些示例,但仍然无法使其工作,没有数据添加到服务器。
这是我的代码:
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStream stream = connection.getOutputStream();
stream.write(requestJSON.toString().getBytes());
stream.flush();
stream.close();
更新
我注意到当我尝试在stream.close()
之后读取响应时代码有效,例如:
connection.getResponseMessage()
这是否意味着必须阅读回复才能完成请求?
答案 0 :(得分:1)
使用此
如果请求是GET
findAll(Specification)
//如果请求已发布
public static String getDataUsingGetRequest(String urlVal) {
String Content = null;
BufferedReader reader = null;
try {
URL url = new URL(urlVal);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(15 * 1000);
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
Content = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return Content;
}