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.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params,
        boolean retry, String accessToken) throws IOException {
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request = null;//from  w  ww  . ja  v a  2s.c o m

        if (verb == RequestVerb.POST || verb == RequestVerb.PUT) {
            switch (verb) {
            case POST:
                request = new HttpPost(url);
                break;
            case PUT:
                request = new HttpPut(url);
                break;
            default:
                throw new RuntimeException("RequestVerb not implemented: " + verb);
            }

            List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>();

            if (params != null) {
                List<BasicNameValuePair> convertedParams = convertParams(params);
                paramsBody.addAll(convertedParams);
            }

            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8"));
        } else {
            if (params != null) {
                url = url + "?" + createRequestParams(params);
            }

            if (verb == RequestVerb.GET) {
                request = new HttpGet(url);
            } else if (verb == RequestVerb.DELETE) {
                request = new HttpDelete(url);
            }
        }
        if (request == null)
            return null;

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));
        System.out.println("auth header: " + request.getFirstHeader("Authorization"));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, params, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String paramStr = createRequestParams(params);
    String url = BASE_URL + method;

    if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE)
        url += "?" + paramStr;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) {
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(paramStr);
        writer.flush();
        writer.close();
    }

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, params, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:com.spotify.helios.client.DefaultHttpConnector.java

private static void handleHttps(final HttpURLConnection connection, final String hostname,
        final HostnameVerifierProvider hostnameVerifierProvider, final HttpsHandler extraHttpsHandler) {

    if (!(connection instanceof HttpsURLConnection)) {
        return;/*from ww w . j  ava 2s .c  o  m*/
    }

    // We verify the TLS certificate against the original hostname since verifying against the
    // IP address will fail
    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
    connection.setRequestProperty("Host", hostname);

    final HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
    httpsConnection.setHostnameVerifier(hostnameVerifierProvider.verifierFor(hostname));

    if (extraHttpsHandler != null) {
        extraHttpsHandler.handle(httpsConnection);
    }
}

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

/**
 * ?http?//from  w w  w. ja va2  s  .  co  m
 * @param url
 * @param method
 * @param headers
 * @return
 * @throws IOException
 */
private static HttpURLConnection initHttp(String url, String method, Map<String, String> headers)
        throws IOException {
    URL _url = new URL(url);
    HttpURLConnection http = (HttpURLConnection) _url.openConnection();
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:dlauncher.authorization.DefaultCredentialsManager.java

private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors)
        throws ProtocolException, IOException, AuthorizationException {
    JSONObject obj = null;//w  ww.j a  v a2s. c  o m
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(15 * 1000);
        con.setReadTimeout(15 * 1000);
        con.connect();
        try (OutputStream out = con.getOutputStream()) {
            out.write(post.toString().getBytes(Charset.forName("UTF-8")));
        }
        con.getResponseCode();
        InputStream instr;
        instr = con.getErrorStream();
        if (instr == null) {
            instr = con.getInputStream();
        }
        byte[] data = new byte[1024];
        int length;
        try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) {
            try (InputStream in = new BufferedInputStream(instr)) {
                while ((length = in.read(data)) >= 0) {
                    bytes.write(data, 0, length);
                }
            }
            byte[] rawBytes = bytes.toByteArray();
            if (rawBytes.length != 0) {
                obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8")));
            } else {
                obj = new JSONObject();
            }
            if (!ignoreErrors && obj.has("error")) {
                String error = obj.getString("error");
                String errorMessage = obj.getString("errorMessage");
                String cause = obj.optString("cause", null);
                if ("ForbiddenOperationException".equals(error)) {
                    if ("UserMigratedException".equals(cause)) {
                        throw new UserMigratedException(errorMessage);
                    }
                    throw new ForbiddenOperationException(errorMessage);
                }
                throw new AuthorizationException(
                        error + (cause != null ? "." + cause : "") + ": " + errorMessage);
            }
            return obj;
        }
    } catch (JSONException ex) {
        throw new InvalidResponseException(ex, obj);
    }
}

From source file:com.vaguehope.onosendai.util.HttpHelper.java

private static <R> R fetchWithFollowRedirects(final Method method, final URL url,
        final HttpStreamHandler<R> streamHandler, final int redirectCount)
        throws IOException, URISyntaxException {
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {/*from w  w  w .  ja va 2  s. c  om*/
        connection.setRequestMethod(method.toString());
        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS));
        connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS));
        connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser.
        //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong.
        connection.connect();

        InputStream is = null;
        try {
            final int responseCode = connection.getResponseCode();

            // For some reason some devices do not follow redirects. :(
            if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers.  Its HTTP spec.
                if (redirectCount >= MAX_REDIRECTS)
                    throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS);
                final String locationHeader = connection.getHeaderField("Location");
                if (locationHeader == null)
                    throw new HttpResponseException(responseCode,
                            "Location header missing.  Headers present: " + connection.getHeaderFields() + ".");
                connection.disconnect();

                final URL locationUrl;
                if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) {
                    locationUrl = new URL(locationHeader);
                } else {
                    locationUrl = url.toURI().resolve(locationHeader).toURL();
                }
                return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1);
            }

            if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers.  Its HTTP spec.
                throw new NotOkResponseException(responseCode, connection, url);
            }

            is = connection.getInputStream();
            final int contentLength = connection.getContentLength();
            if (contentLength < 1)
                LOG.w("Content-Length=%s for %s.", contentLength, url);
            return streamHandler.handleStream(connection, is, contentLength);
        } finally {
            IoHelper.closeQuietly(is);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonResult readLink(String urlString, String method, boolean breakRoute) {
    JsonResult result = new JsonResult();
    if (urlString == null) {
        return result;
    }/*w w w  .jav a 2 s .com*/
    URL url = null;
    HttpURLConnection httpget = null;
    try {
        LOG.d("HttpUtils readlink() " + urlString);
        url = new URL(urlString);
        httpget = (HttpURLConnection) url.openConnection();
        httpget.setDoInput(true);
        httpget.setRequestMethod(method);
        if (breakRoute) {
            httpget.setRequestProperty("Accept", "application/vnd.ibikecph.v1");
        } else {
            httpget.setRequestProperty("Accept", "application/json");
        }
        httpget.setConnectTimeout(CONNECTON_TIMEOUT);
        httpget.setReadTimeout(CONNECTON_TIMEOUT);
        JsonNode 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;
    } catch (Exception e) {
    } finally {
        if (httpget != null) {
            httpget.disconnect();
        }
    }
    LOG.d("HttpUtils readLink() "
            + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed"));
    return result;
}

From source file:com.iStudy.Study.Renren.Util.java

private static HttpURLConnection openConn(String url, String method, Bundle params) {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }//from   w ww. ja  v  a2s .  c om
    try {
        Log.d(LOG_TAG, method + " URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent", USER_AGENT_SDK);
        if (!method.equals("GET")) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }
        return conn;
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.android.tools.idea.structure.MavenDependencyLookupDialog.java

@NotNull
private static List<String> searchMavenCentral(@NotNull String text) {
    try {/*from   w ww.j av a2s  .  co  m*/
        String url = String.format(MAVEN_CENTRAL_SEARCH_URL, RESULT_LIMIT, text);
        final HttpURLConnection urlConnection = HttpConfigurable.getInstance().openHttpConnection(url);
        urlConnection.setConnectTimeout(SEARCH_TIMEOUT);
        urlConnection.setReadTimeout(SEARCH_TIMEOUT);
        urlConnection.setRequestProperty("accept", "application/xml");

        InputStream inputStream = urlConnection.getInputStream();
        Document document;
        try {
            document = new SAXBuilder().build(inputStream);
        } finally {
            inputStream.close();
        }
        XPath idPath = XPath.newInstance("str[@name='id']");
        XPath versionPath = XPath.newInstance("str[@name='latestVersion']");
        List<Element> artifacts = (List<Element>) XPath.newInstance("/response/result/doc")
                .selectNodes(document);
        List<String> results = Lists.newArrayListWithExpectedSize(artifacts.size());
        for (Element element : artifacts) {
            try {
                String id = ((Element) idPath.selectSingleNode(element)).getValue();
                String version = ((Element) versionPath.selectSingleNode(element)).getValue();
                results.add(id + ":" + version);
            } catch (NullPointerException e) {
                // A result is missing an ID or version. Just skip it.
            }
        }
        return results;
    } catch (JDOMException e) {
        LOG.warn(e);
    } catch (IOException e) {
        LOG.warn(e);
    }
    return Collections.emptyList();
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry,
        String accessToken) throws IOException, UnsupportedRequestVerbException {

    if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) {
        throw new UnsupportedRequestVerbException();
    }/*  w w w  .  ja  v a 2  s .c om*/
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request;

        switch (verb) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        default:
            throw new RuntimeException("RequestVerb not implemented: " + verb);
        }

        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));

        request.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, json, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String url = BASE_URL + method;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());
    conn.addRequestProperty("Content-Type", "application/json");

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(json.toString());
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, json, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static HttpURLConnection doRequest(String endpoint, CypherSession session, String[] keys,
        String[] values) throws IOException {
    HttpURLConnection connection = (java.net.HttpURLConnection) new URL(DOMAIN + endpoint).openConnection();
    connection.setDoOutput(true);//w ww.j  a v  a  2 s .c o m
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    connection.connect();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
    if (session != null) {
        writer.write("userID=");
        writer.write(session.getUser().getUserID() + "&sessionID=");
        writer.write(session.getSessionID());
    }
    if (keys != null && keys.length > 0) {
        if (session != null) {
            writer.write('&');
        }
        // write first row
        writer.write(keys[0]);
        writer.write('=');
        writer.write(URLEncoder.encode(values[0], "UTF-8"));
        for (int i = 1; i < keys.length; i++) {
            writer.write('&');
            writer.write(keys[i]);
            writer.write('=');
            writer.write(URLEncoder.encode(values[i], "UTF-8"));
        }
    }
    writer.close();
    return connection;
}