简体   繁体   中英

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

I need to send a post request to url which is formed as follows:

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

Using HttpPost client in java, how can post request to such query strings I could connect from javascript easily through ajax but from java client, it's failing.

(I know sending querystring in post request is stupid idea. Since I am connecting to someone else's server I cannot not change the way it is)

Here is one way to send JSON in a POST request using Java (without Apache libraries). You might find this helpful:

//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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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