Example usage for java.net HttpURLConnection setRequestProperty

List of usage examples for java.net HttpURLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net HttpURLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

public static String deleteServer(String host, String tenantId, String token, String serverId)
        throws IOException {

    String url = String.format("http://%s:8774/v2/%s/servers", host, tenantId);

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("DELETE");
    con.setRequestProperty("tenant_id", tenantId);
    con.setRequestProperty("server_id", serverId);

    String responseStr = sendDELETE(obj, con);
    System.out.println(responseStr);

    return responseStr;

}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

private static String sendPOST(URL url, HttpURLConnection con, String body) throws IOException {

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-type", "application/json");
    con.setRequestProperty("Accept", "application/json");

    con.setDoOutput(true);//from w  w w  .  java2s  . c om
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();

    logger.log(Level.INFO, "Sending POST request to URL : {0}", url);
    int responseCode = con.getResponseCode();
    logger.log(Level.INFO, "Response Code : {0}", responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder responseStr = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        responseStr.append(inputLine);
    }
    in.close();

    return responseStr.toString();

}

From source file:io.cloudex.cloud.impl.google.compute.GoogleMetaData.java

/**
 * Call the metadata server, this returns details for the current instance not for
 * different instances. In order to retrieve the meta data of different instances
 * we just use the compute api, see getInstance
 * @param path/*from ww  w  . j  a v  a 2  s  .  c  o  m*/
 * @return
 * @throws IOException
 */
public static String getMetaData(String path) throws IOException {
    log.debug("Retrieving metadata from server, path: " + path);
    URL metadata = new URL(METADATA_SERVER_URL + path);
    HttpURLConnection con = (HttpURLConnection) metadata.openConnection();

    // optional default is GET
    //con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("Metadata-Flavor", "Google");

    int responseCode = con.getResponseCode();

    StringBuilder response = new StringBuilder();

    if (responseCode == 200) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }
    } else {
        String msg = "Metadata server responded with status code: " + responseCode;
        log.error(msg);
        throw new IOException(msg);
    }
    log.debug("Successfully retrieved metadata from server");

    return response.toString();
}

From source file:Main.java

public static String executePost(String targetURL, String urlParameters) {
    try {//from  www .  ja  va  2s.c  om
        HttpURLConnection connection = (HttpURLConnection) new URL(targetURL).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        //connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(urlParameters.getBytes());
        } finally {
            if (output != null)
                try {
                    output.flush();
                    output.close();
                } catch (IOException logOrIgnore) {
                }
        }
        InputStream response = connection.getInputStream();
        String contentType = connection.getHeaderField("Content-Type");
        String responseStr = "";
        if (true) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(response));
                for (String line; (line = reader.readLine()) != null;) {
                    //System.out.println(line);
                    responseStr = responseStr + line;
                    Thread.sleep(2);
                }
            } finally {
                if (reader != null)
                    try {
                        reader.close();
                    } catch (IOException logOrIgnore) {
                    }
            }
        } else {
            // It's likely binary content, use InputStream/OutputStream.
            System.out.println("Binary content");
        }
        return responseStr;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:net.line2soft.preambul.utils.Network.java

/**
 * Checks if a connection is possible between device and server.
 * @param address The URL to request/*from  w ww .  jav  a  2  s .com*/
 * @return True if the connection is possible, false else
 */
public static boolean checkConnection(URL address) {
    boolean result = false;
    try {
        HttpURLConnection urlc = (HttpURLConnection) address.openConnection();
        //urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000);
        urlc.connect();
        if (urlc.getResponseCode() == 200) {
            result = true;
        }
    } catch (Exception e) {
        ;
    }
    return result;
}

From source file:RemoteDeviceDiscovery.java

public static void postDevice(RemoteDevice d) throws Exception {
    String url = "http://bluetoothdatabase.com/datacollection/";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "blucat");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = deviceJson(d);

    // Send post request
    con.setDoOutput(true);// w  ww .j a  v a2s  .co m
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    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();
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPostRegisterUser(String url, String registerParam, Map<String, String> cobTokens,
        boolean isEncodingNeeded) throws IOException {
    //String processedURL = url+"?registerParam="+registerParam;
    /* String registerUserJson="{"
    + "      \"user\" : {"/* w ww .  j av  a  2s.c o  m*/
    + "            \"loginName\" : \"TestT749\","
    + "            \"password\" : \"TESTT@123\","
    + "            \"email\" : \"testet@yodlee.com\","
    + "            \"firstName\" : \"Rehhsty\","
    + "            \"lastName\" :\"ysl\""
    +"             } ,"
            
    + "      \"preference\" : {"
    + "      \"address\" : {"
    + "            \"street\" : \"abcd\","
    + "            \"state\" : \"CA\","
    + "            \"city\" : \"RWS\","
    + "            \"postalCode\" : \"98405\","
    + "            \"countryIsoCode\" : \"USA\""
    +"             } ,"
    + "            \"currency\" : \"USD\","
    + "            \"timeZone\" : \"PST\","
    + "            \"dateFormat\" : \"MM/dd/yyyy\""
    + "}"
    + "}";*/

    //encoding url
    registerParam = java.net.URLEncoder.encode(registerParam, "UTF-8");
    String processedURL = url + "?registerParam=" + registerParam;
    String mn = "doIO(POST : " + processedURL + ", " + registerParam + "sessionTokens : " + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(processedURL);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
    conn.setRequestProperty("Authorization", cobTokens.toString());
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    int responseCode = conn.getResponseCode();
    if (responseCode == 200) {
        System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request");
        System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder jsonResponse = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            jsonResponse.append(inputLine);
        }
        in.close();
        System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
        return new String(jsonResponse);
    } else {
        System.out.println("Invalid input");
        return new String();

    }
}

From source file:com.github.terma.m.node.Node.java

private static void send(final String serverHost, final int serverPort, final String context,
        final List<Event> events) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) new URL("http", serverHost, serverPort,
            context + "/node").openConnection();
    connection.setDoOutput(true);/*from  ww  w  .j  ava2s . com*/
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/json");
    connection.setRequestProperty("charset", "utf-8");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.connect();
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(new Gson().toJson(events).getBytes());
    connection.getInputStream().read();
    outputStream.close();
}

From source file:flow.visibility.tapping.OpenDayLightUtils.java

/** The function for inserting the flow */

public static void FlowEntry(String ODPURL, String ODPAccount, String ODPPassword) throws Exception {

    //String user = "admin";
    //String password = "admin";
    String baseURL = "http://" + ODPURL + "/controller/nb/v2/flowprogrammer";
    String containerName = "default";

    /** Check the connection for ODP REST API */

    try {/*from  w w  w . jav  a2  s.  com*/

        // Create URL = base URL + container
        URL url = new URL(baseURL + "/" + containerName);

        // Create authentication string and encode it to Base64
        String authStr = ODPAccount + ":" + ODPPassword;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        // Create Http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // Set connection properties
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Accept", "application/json");

        // Get the response from connection's inputStream
        InputStream content = (InputStream) connection.getInputStream();

        /** The create the frame and blank pane */
        OpenDayLightUtils object = new OpenDayLightUtils();
        object.setVisible(true);

        /** Read the Flow entry in JSON Format */
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";

        /** Print line by line in Pane with Pretty JSON */
        while ((line = in.readLine()) != null) {

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);

            Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
            String json = gson.toJson(jsonObject);
            System.out.println(json);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.heraldapp.share.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //from   w  ww .ja v  a 2 s. co m
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    String response = "";
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(10000);
        if (!method.equals("GET")) {
            // use method override
            params.putString("method", method);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }

        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    } catch (SocketTimeoutException e) {
        return response;
    }
    return response;
}