繁体   English   中英

使用Java中的HttpPost客户端将带有查询字符串的HTTP发布请求发送到URL

[英]Send http post request to URL with query string using HttpPost client in java

我需要向网址发送发帖请求,其格式如下:

www.abc.com/service/postsomething?data={'name':'rikesh'}&id=45

在Java中使用HttpPost客户端,如何将请求发布到这样的查询字符串,我可以通过Ajax从javascript轻松连接,但是从Java客户端失败。

(我知道在发布请求中发送查询字符串是愚蠢的主意。由于我正在连接到其他人的服务器,因此无法更改其方式)

这是使用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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM