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:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *///from w  w  w.  j a va 2  s.  c o  m
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:net.cbtltd.server.WebService.java

/**
 * Gets the connection to the JSON server.
 *
 * @param url the connection URL./* www. j av  a 2  s.c om*/
 * @param rq the request object.
 * @return the JSON string returned by the message.
 * @throws Throwable the exception thrown by the method.
 */
private static final String getConnection(URL url, String rq) throws Throwable {
    String jsonString = "";
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        //connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");

        if (rq != null) {
            connection.setRequestProperty("Accept", "application/json");
            connection.connect();
            byte[] outputBytes = rq.getBytes("UTF-8");
            OutputStream os = connection.getOutputStream();
            os.write(outputBytes);
        }

        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("HTTP:" + connection.getResponseCode() + "URL " + url);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        String line;
        while ((line = br.readLine()) != null) {
            jsonString += line;
        }
    } catch (Throwable x) {
        throw new RuntimeException(x.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return jsonString;
}

From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java

/**
 * Opens a POST connection./*from  w  ww  .  j a va  2s  .  c  o m*/
 *
 * @param url The URL to connect to.
 *
 * @return A POST connection to this URL.
 * @throws IOException If an exception occurred while contacting the server.
 */
static private HttpURLConnection getPOSTConnection(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    return connection;
}

From source file:oneDrive.OneDriveAPI.java

public static String connectWithREST(String url, String method) throws IOException, ProtocolException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);/*from ww w . j a v a 2s.com*/
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT) || getSize)
        con.addRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();

    return newURL;
}

From source file:com.baasbox.service.push.providers.GCMServer.java

public static void validateApiKey(String apikey)
        throws MalformedURLException, IOException, PushInvalidApiKeyException {
    Message message = new Message.Builder().addData("message", "validateAPIKEY").build();
    Sender sender = new Sender(apikey);

    List<String> deviceid = new ArrayList<String>();
    deviceid.add("ABC");

    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    jsonRequest.put(JSON_REGISTRATION_IDS, deviceid);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }/*  w  ww . ja v a  2  s . com*/
    String requestBody = JSONValue.toJSONString(jsonRequest);

    String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    byte[] bytes = requestBody.getBytes();

    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + apikey);
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    int status = conn.getResponseCode();
    if (status != 200) {
        if (status == 401) {
            throw new PushInvalidApiKeyException("Wrong api key");
        }
        if (status == 503) {
            throw new UnknownHostException();
        }
    }

}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

public static String postFiles(String url, Map<String, String> vars, Map<String, File> files) {
    try {/* w  w  w. j  a  v  a  2  s.  c  o m*/
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        assembleMultipartFiles(out, vars, files);

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        return "Encoding exception: " + e;
    } catch (IOException e) {
        return "IOException: " + e;
    } catch (IllegalStateException e) {
        return "IllegalState: " + e;
    }
}

From source file:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendGet(String url) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;//from   ww  w. j  a v  a  2  s  .  c  o  m
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

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

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

            }
        }
        if (con != null) {
            con.disconnect();
        }
    }

}

From source file:com.edgenius.wiki.Shell.java

/**
 * @param url//from w w w .jav a2 s .c o  m
 * @return
 */
private static boolean notifyShell(String url) {
    if (StringUtils.isEmpty(Shell.key)) {
        //I suppose all notify methods will execute in backend thread, i.e.,  MQ consumer. This won't use new thread to avoid thread block.  
        if (!requestInstanceShellKey()) {
            log.error("Unable to locate Shell key value from shell hosting {}", url);
            return false;
        }
    }

    try {
        log.info("Notify shell {}", url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty(HEAD_SHELL_KEY, Shell.key);

        conn.setConnectTimeout(timeout);
        return (conn.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (IOException e) {
        log.error("Unable to connect shell for notification", e);
    } catch (Throwable e) {
        log.error("Notify shell failure", e);
    }

    return false;
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *//*from w ww  .j  a va2 s . com*/
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        urlConnection.connect();
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } catch (IOException e) {
        String details;
        if (urlConnection != null) {
            details = "; code=" + urlConnection.getResponseCode() + " (" + urlConnection.getResponseMessage()
                    + ")";
        } else {
            details = "";
        }
        Log.e("ExoplayerUtil", "executePost: Request failed" + details, e);
        throw e;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:Main.java

/**
 * Executes a post request using {@link HttpURLConnection}.
 *
 * @param url The request URL./*from   w  ww. j  a  v  a 2  s . c o  m*/
 * @param data The request body, or null.
 * @param requestProperties Request properties, or null.
 * @return The response body.
 * @throws IOException If an error occurred making the request.
 */
// TODO: Remove this and use HttpDataSource once DataSpec supports inclusion of a POST body.
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        // Write the request body, if there is one.
        if (data != null) {
            OutputStream out = urlConnection.getOutputStream();
            try {
                out.write(data);
            } finally {
                out.close();
            }
        }
        // Read and return the response body.
        InputStream inputStream = urlConnection.getInputStream();
        try {
            return toByteArray(inputStream);
        } finally {
            inputStream.close();
        }
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}