我有从 url 解析 json 内容并完成它们的 android 要求,现在我需要将结果作为 json 内容发送回服务器 url。搜索了许多以前的帖子,但大多数都指定了如何下载和解析 json 内容。任何关于如何开始在 json 中将内容发布到 url 的输入/示例都会有很大的帮助!
编辑:下面是我正在尝试的示例代码
try {
URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
执行此操作时,连接被拒绝,java.net.connect 异常!请帮忙!!