我需要向url发送一个post请求,其形式如下:
www.abc.com/service/postsomething?data = {'名称':' rikesh'}和ID = 45
在java中使用HttpPost客户端,如何向这样的查询字符串发布请求 我可以通过ajax轻松地通过ajax连接,但是从java客户端,它失败了。
(我知道在post post中发送查询字符串是个愚蠢的想法。因为我连接到别人的服务器我不能改变它的方式)
答案 0 :(得分:0)
这是使用Java(没有Apache库)在POST请求中发送JSON的一种方法。您可能会发现这有用:
//init
String json = "{\"name\":\"rikesh\"}";
String requestString = "http://www.example.com/service/postsomething?id=45";
//send request
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
int responseCode = conn.getResponseCode();
//get result if there is one
if(responseCode == 200) //HTTP 200: Response OK
{
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while((output = br.readLine()) != null)
{
result += output;
}
System.out.println("Response message: " + result);
}