簡體   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