简体   繁体   中英

Java: Open a new window with Headers and POST parameters

I'm using java 1.7 on Tomcat 7, I can send POST request with this code:

private void processSelectProductOnChange(ActionEvent e) {
    URL obj;
    HttpURLConnection con;
    String urlParameters = "";
    String url = "http://myservice.example.com/Service/New";
    String userAgent = request.getHeader("User-Agent");
    int accountId = 5;
    try {
        obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", userAgent);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("ServiceName", "myServiceName");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        String json = getJSONObject(accountId);
        wr.writeUTF(json);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
}

private String getJSONObject(int accountId) throws UnsupportedEncodingException
    {
        JSONObject jobj = new JSONObject();
        jobj.put("AccountId", String.valueOf(accountId));
        jobj.put("ServiceId", String.valueOf(2));
        jobj.put("ExpirationDate", "");
        jobj.put("Description", "");
        return jobj.toString();
    }

Now instead of send a POST request, I'd like to open a new browser window to the URL from my web application, how can I do that?

Edit: I forgot to say that I'd like to do the POST request while the new browser Tab is opening.

As far as I know you can't directly send a POST request using the address bar of a browser. You may need to use a plugin like Postman, Advanced REST client. Or you can use direct HttpURLConnection or a http client library.

But if you want to open the default web browser through your program you can do as follows (for GET request)

if(Desktop.isDesktopSupported())
{
  Desktop.getDesktop().browse(new URI(your url here));
}

Otherwise you can create a Process and start the browser.

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