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:com.rutarget.UpsourceReviewStatsExtension.PageExtension.java

private static <T> T request(String method, @Nullable Object parameter, Class<T> clazz) throws IOException {
    String address = UPSOURCE_API_URL + method;
    URL url = new URL(address);
    @SuppressWarnings("ConstantConditions")
    HttpURLConnection c = (HttpURLConnection) (PROXY != null ? url.openConnection(PROXY)
            : url.openConnection());// w ww  .ja  v  a 2s  .c o m
    String authString = UPSOURCE_USERNAME + ":" + UPSOURCE_PASSWORD;
    //Base64 doesn't look thread safe, therefore we create new instance for each occasion
    c.setRequestProperty("Authorization", "Basic " + new String(new Base64().encode(authString.getBytes())));

    if (parameter != null) {
        String output = GSON.toJson(parameter);
        c.setDoOutput(true);
        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/json");
        c.setRequestProperty("Content-Length", String.valueOf(output.length()));
        c.getOutputStream().write(output.getBytes("UTF-8"));
    }
    InputStream inputStream = c.getInputStream();
    String response = IOUtils.toString(inputStream);
    try {
        JsonObject element = (JsonObject) new JsonParser().parse(response);
        return GSON.fromJson(element.get("result"), clazz);
    } catch (Exception e) {
        throw new IOException(
                "Failed to parse response " + escapeToHtmlAttribute(response) + ": " + e.getMessage());
    }
}

From source file:com.delicious.deliciousfeeds4J.DeliciousUtil.java

public static String expandShortenedUrl(String shortenedUrl, String userAgent) throws IOException {

    if (shortenedUrl == null || shortenedUrl.isEmpty())
        return shortenedUrl;

    if (userAgent == null || userAgent.isEmpty())
        throw new IllegalArgumentException("UserAgent must not be null or empty!");

    if (shortenedUrl.contains(URL_SHORTENED_SNIPPET) == false)
        return shortenedUrl;

    logger.debug("Trying to expand shortened url: " + shortenedUrl);

    final URL url = new URL(shortenedUrl);

    final HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);

    try {//from   w w w.ja  v a  2 s.c  o  m
        connection.setInstanceFollowRedirects(false);
        connection.setRequestProperty("User-Agent", userAgent);
        connection.connect();
        final String expandedDeliciousUrl = connection.getHeaderField("Location");

        if (expandedDeliciousUrl.contains("url=")) {

            final Matcher matcher = URL_PARAMETER_PATTERN.matcher(expandedDeliciousUrl);

            if (matcher.find()) {
                final String expanded = matcher.group();

                logger.trace("Successfully expanded: " + shortenedUrl + " -> " + expandedDeliciousUrl + " -> "
                        + expanded);

                return expanded;
            }
        }
    } catch (Exception ex) {
        logger.debug("Error while trying to expand shortened url: " + shortenedUrl, ex);
    } finally {
        connection.getInputStream().close();
    }

    return shortenedUrl;
}

From source file:com.spoiledmilk.ibikecph.util.HttpUtils.java

public static JsonResult readLink(String url_string, String method) {
    JsonResult result = new JsonResult();
    if (url_string == null) {
        return result;
    }/*from  ww w.j  a  v  a 2s . co  m*/
    URL url = null;
    HttpURLConnection httpget = null;
    try {
        LOG.d("HttpUtils readlink() " + url_string);
        url = new URL(url_string);
        httpget = (HttpURLConnection) url.openConnection();
        httpget.setDoInput(true);
        httpget.setRequestMethod(method);
        httpget.setRequestProperty("Accept", "application/json");
        httpget.setRequestProperty("Content-type", "application/json");
        httpget.setConnectTimeout(CONNECTON_TIMEOUT);
        httpget.setReadTimeout(CONNECTON_TIMEOUT);
        JsonNode root = null;
        root = Util.getJsonObjectMapper().readValue(httpget.getInputStream(), JsonNode.class);
        if (root != null) {
            result.setNode(root);
        }
    } catch (JsonParseException e) {
        LOG.w("HttpUtils readLink() JsonParseException ", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (MalformedURLException e) {
        LOG.w("HttpUtils readLink() MalformedURLException", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (FileNotFoundException e) {
        LOG.w("HttpUtils readLink() FileNotFoundException", e);
        result.error = JsonResult.ErrorCode.NotFound;
    } catch (IOException e) {
        LOG.w("HttpUtils readLink() IOException", e);
        result.error = JsonResult.ErrorCode.ConnectionError;
    } finally {
        if (httpget != null) {
            httpget.disconnect();
        }
    }
    LOG.d("HttpUtils readLink() "
            + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed"));
    return result;
}

From source file:no.ntnu.wifimanager.ServerUtilities.java

/**
 * Issue a POST request to server./*from   w  w  w .  ja  va2  s. co  m*/
 *
 * @param serverUrl POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(serverUrl);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + serverUrl);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(LOG_TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", contentType);
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();

        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified/* w  ww  .j  a v  a 2 s .  c o  m*/
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java

private static HttpURLConnection makePostConnection(URL url, byte[] bytes) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/*from  w w w . java2 s  .  c o m*/
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    // Add in API key
    String authKey = new String(Base64.encodeBase64((key + ":").getBytes()));
    conn.setRequestProperty("Authorization", "Basic " + authKey);

    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    return conn;
}

From source file:de.darkblue.bongloader2.utils.ToolBox.java

/**
 * returns the file size using the config to retrieve the current version of
 * bongloader and setting the right user-agent
 *
 * @param config//from www. j  a v  a2s  .com
 * @param url
 * @return
 * @throws IOException
 */
public static long getFileSize(final Configuration config, final URL url) throws IOException {
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        if (config != null) {
            connection.setRequestProperty("User-Agent", "BongLoader2 " + config.get(ConfigurationKey.VERSION));
        }
        connection.setConnectTimeout(2000);
        connection.connect();

        final String headerField = connection.getHeaderField("Content-Length");
        if (headerField == null) {
            throw new IOException("Did not get a content length for the connection to " + url);
        }

        final String rawContentLength = headerField.trim();
        return Long.valueOf(rawContentLength);
        //return connection.getContentLength();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public static String getRedirectUrl(REGION region) {
    String result = "";

    switch (region) {
    case EU:/*from www .ja v a 2  s .co  m*/
        result = amazonEuDomain;
        break;
    case USA:
        result = amazonUsaDomain;
        break;
    case ASIA:
        result = amazonAsiaDomain;
        break;
    }

    System.out.println("Trying to get real IP address of " + result);
    try {
        /*
        HttpHead headRequest = new HttpHead(result);
        HttpClient client = new DefaultHttpClient();
         HttpResponse response = client.execute(headRequest);
         final int statusCode = response.getStatusLine().getStatusCode();
         if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
             statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
         {
             String location = response.getHeaders("Location")[0].toString();
             String redirecturl = location.replace("Location: ", "");
             result = redirecturl;
         }
        */

        URL url = new URL(result);
        HttpURLConnection httpGetCon = (HttpURLConnection) url.openConnection();
        httpGetCon.setInstanceFollowRedirects(false);
        httpGetCon.setRequestMethod("GET");
        httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds

        httpGetCon.setRequestProperty("User-Agent", USER_AGENT);

        int status = httpGetCon.getResponseCode();
        System.out.println("code: " + status);
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            result = httpGetCon.getHeaderField("Location");

    } catch (Exception e) {
        System.out.println("Exception is fired in redirector getter. error:" + e.getMessage());
        e.printStackTrace();
    }
    System.out.println("Real IP address is " + result);
    return result;
}

From source file:net.mceoin.cominghome.api.NestUtil.java

/**
 * Make HTTP/JSON call to Nest and set away status.
 *
 * @param access_token OAuth token to allow access to Nest
 * @param structure_id ID of structure with thermostat
 * @param away_status Either "home" or "away"
 * @return Equal to "Success" if successful, otherwise it contains a hint on the error.
 *//*from  w w  w.  ja  va  2 s .  c o  m*/
public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) {

    String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth="
            + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("PUT");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);

        urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        String payload = "\"" + away_status + "\"";

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(payload);
        wr.flush();
        log.info(payload);

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            urlConnection.setRequestProperty("Accept", "application/json");

            //                System.out.println("Redirect to URL : " + newUrl);

            wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(payload);
            wr.flush();

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;
        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    if (error) {
        return "Error: " + errorResult;
    } else {
        return "Success";
    }
}

From source file:com.gson.util.HttpKit.java

/**
 * //from w w  w  .  ja  v a  2  s  .  c o m
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?  
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??  
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); //  
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?  
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}