Example usage for java.net HttpURLConnection addRequestProperty

List of usage examples for java.net HttpURLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:ai.grakn.client.LoaderClient.java

/**
 * Set POST request to host containing information
 * to execute a Loading Tasks with the insert queries as the body of the request
 *
 * @return A Completable future that terminates when the task is finished
 *//* w ww .j  a v a2 s .c om*/
private String executePost(String body) throws HttpRetryException {
    HttpURLConnection connection = null;
    try {
        URL url = new URL(format(POST, uri) + "?" + getPostParams());

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);

        // create post
        connection.setRequestMethod(REST.HttpConn.POST_METHOD);
        connection.addRequestProperty(REST.HttpConn.CONTENT_TYPE, REST.HttpConn.APPLICATION_POST_TYPE);

        // add body and execute
        connection.setRequestProperty(REST.HttpConn.CONTENT_LENGTH, Integer.toString(body.length()));
        connection.getOutputStream().write(body.getBytes(REST.HttpConn.UTF8));
        connection.getOutputStream().flush();

        // get response
        Json response = Json.read(readResponse(connection.getInputStream()));

        return response.at("id").asString();
    } catch (IOException e) {
        if (retry) {
            return executePost(body);
        } else {
            throw new RuntimeException(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(uri));
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.jared.synodroid.ds.server.SimpleSynoServer.java

/**
 * Create a connection and add all required cookies information
 * /* www  .j a v  a2 s .  c o  m*/
 * @param uriP
 * @param requestP
 * @param methodP
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
protected HttpURLConnection createConnection(String uriP, String requestP, String methodP, boolean log)
        throws MalformedURLException, IOException {
    // Prepare the connection
    HttpURLConnection con = (HttpURLConnection) new URL(getUrl() + Uri.encode(uriP, "/")).openConnection();

    // Add cookies if exist
    if (cookies != null) {
        con.addRequestProperty("Cookie", getCookies());
        if (DEBUG)
            Log.v(Synodroid.DS_TAG, "Added cookie to the request: " + cookies);
    }
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setUseCaches(false);
    con.setRequestMethod(methodP);
    con.setConnectTimeout(20000);
    if (DEBUG) {
        if (log) {
            Log.i(Synodroid.DS_TAG, methodP + ": " + uriP + "?" + requestP);
        } else {
            Log.i(Synodroid.DS_TAG, methodP + ": " + uriP + " (hidden request)");
        }
    }
    return con;
}

From source file:com.volley.air.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<>();
    map.putAll(request.getHeaders());/*from  w w w  .  j a va  2 s .  c o  m*/
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    if (!TextUtils.isEmpty(mUserAgent)) {
        connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent);
    }

    for (Entry<String, String> entry : map.entrySet()) {
        connection.addRequestProperty(entry.getKey(), entry.getValue());
    }
    if (request instanceof MultiPartRequest) {
        setConnectionParametersForMultipartRequest(connection, request);
    } else {
        setConnectionParametersForRequest(connection, request);
    }

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

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

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String endpointHost) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {/*from  w w  w .  j av  a  2s . c o  m*/
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final HttpURLConnection connection = (HttpURLConnection) ipUri.toURL().openConnection();
    handleHttps(connection, endpointHost, hostnameVerifierProvider, extraHttpsHandler);

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout(httpTimeoutMillis);
    connection.setReadTimeout(httpTimeoutMillis);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }

    setRequestMethod(connection, method, connection instanceof HttpsURLConnection);

    return connection;
}

From source file:org.overlord.gadgets.web.server.servlets.RestProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w w  w.j ava 2 s.c om
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("Proxy inbound endpoint: " + req.getRequestURI());
    // Connect to proxy URL.
    String urlStr = getProxyUrl(req);
    String queryString = req.getQueryString();
    if (queryString != null) {
        urlStr = urlStr + "?" + queryString;
    }
    System.out.println("Proxying to: " + urlStr);
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    // Proxy all of the request headers.
    Enumeration<?> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = String.valueOf(headerNames.nextElement());
        Enumeration<?> headerValues = req.getHeaders(headerName);
        while (headerValues.hasMoreElements()) {
            String headerValue = String.valueOf(headerValues.nextElement());
            conn.addRequestProperty(headerName, headerValue);
        }
    }

    // Handle authentication
    RestProxyAuthProvider authProvider = getAuthProvider();
    if (authProvider != null) {
        authProvider.provideAuthentication(conn);
    }

    // Now connect and proxy the response.
    InputStream proxyUrlResponseStream = null;
    try {
        proxyUrlResponseStream = conn.getInputStream();
        resp.setStatus(conn.getResponseCode());
        // Proxy the response headers
        for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
            String respHeaderName = entry.getKey();
            if (respHeaderName != null && !respHeaderName.equalsIgnoreCase("transfer-encoding")) {
                for (String respHeaderValue : entry.getValue()) {
                    resp.addHeader(respHeaderName, respHeaderValue);
                }
            }
        }

        // Proxy the response body.
        IOUtils.copy(proxyUrlResponseStream, resp.getOutputStream());
    } finally {
        IOUtils.closeQuietly(proxyUrlResponseStream);
        conn.disconnect();
    }
}

From source file:org.runnerup.export.JoggSESynchronizer.java

@Override
public Status upload(final SQLiteDatabase db, final long mID) {
    Status s;//from ww w . j a v  a2  s  . c o  m
    if ((s = connect()) != Status.OK) {
        return s;
    }

    Exception ex = null;
    HttpURLConnection conn = null;
    final GPX gpx = new GPX(db);
    try {
        final StringWriter gpxString = new StringWriter();
        gpx.export(mID, gpxString);

        conn = (HttpURLConnection) new URL(BASE_URL).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        conn.addRequestProperty("Host", "jogg.se");
        conn.addRequestProperty("Content-Type", "text/xml; charset=utf-8");

        final BufferedWriter wr = new BufferedWriter(new PrintWriter(conn.getOutputStream()));
        saveGPX(wr, gpxString.toString());
        wr.flush();
        wr.close();

        final InputStream in = new BufferedInputStream(conn.getInputStream());
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder dob = dbf.newDocumentBuilder();
        final InputSource is = new InputSource();
        is.setByteStream(in);
        final Document doc = dob.parse(is);
        conn.disconnect();
        conn = null;

        final String path[] = { "soap:Envelope", "soap:Body", "SaveGpxResponse", "SaveGpxResult",
                "ResponseStatus", "ResponseCode" };
        final Node e = navigate(doc, path);
        Log.e(getName(), "reply: " + e.getTextContent());
        if (e != null && e.getTextContent() != null && "OK".contentEquals(e.getTextContent())) {
            s = Status.OK;
            s.activityId = mID;
            return s;
        }
        throw new Exception(e.getTextContent());
    } catch (final MalformedURLException e) {
        ex = e;
    } catch (final IOException e) {
        ex = e;
    } catch (final ParserConfigurationException e) {
        ex = e;
    } catch (final SAXException e) {
        ex = e;
    } catch (final DOMException e) {
        ex = e;
        e.printStackTrace();
    } catch (final Exception e) {
        ex = e;
    }

    if (conn != null)
        conn.disconnect();

    s = Synchronizer.Status.ERROR;
    s.ex = ex;
    s.activityId = mID;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;

}

From source file:com.wordpress.metaphorm.authProxy.hook.AuthProxyServletFilter.java

private boolean processLocalLiferayResourceRequest(HttpServletRequest servletReq,
        HttpServletResponse servletResp)
        throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException,
        OAuthCommunicationException, IOException, MalformedURLException, UnsupportedEncodingException {

    OAuthState oAuthState = OAuthStateManager.getOAuthState(servletReq.getSession().getId());

    String url = servletReq.getRequestURL().toString();
    String queryString = servletReq.getQueryString();

    if (oAuthState != null) {

        _log.debug("Requesting local Liferay resource using p_auth from OAuthState object!");

        try {//w w  w .jav a2  s.c  om
            if (queryString != null)
                queryString += "&p_auth=" + oAuthState.getPAuth();
            else
                queryString = "p_auth=" + oAuthState.getPAuth();

        } catch (ExpiredStateException e) {
            _log.debug("Could not provide p_auth parameter enrichment");
        }
    }

    _log.debug("Requesting " + url + (queryString != null ? "?" + queryString : ""));

    HttpURLConnection uRLConn = (HttpURLConnection) new URL(
            url + (queryString != null ? "?" + queryString : "")).openConnection();
    uRLConn.addRequestProperty("User-Agent", PROXY_USER_AGENT);

    uRLConn.addRequestProperty("Cookie", "JSESSIONID=" + servletReq.getSession().getId());

    String transformHeader = servletReq.getHeader("transform-response-to");
    if (transformHeader == null)
        transformHeader = servletReq.getParameter("transform-response-to");

    uRLConn.connect();

    int httpStatusCode = uRLConn.getResponseCode();
    servletResp.setStatus(httpStatusCode);

    if (httpStatusCode < 200 || httpStatusCode >= 300) {
        // Return immediately for error codes
        return true;
    }

    InputStream in = uRLConn.getInputStream();

    if (transformHeader != null) {

        _log.debug("Transforming JSON to XML");

        servletResp.setContentType("application/xml");
        String json = sinkInputStream(in, servletResp.getCharacterEncoding());
        Utils.writeJSONAsXML(json, servletResp.getWriter());

    } else {

        // Proxy content type hearder
        servletResp.setContentType(uRLConn.getContentType());

        OutputStream out = servletResp.getOutputStream();

        int i;
        while ((i = in.read()) != -1) {
            out.write((byte) i);
        }

    }

    return true;
}

From source file:org.rhq.modules.plugins.jbossas7.ASConnection.java

/**
 * Execute an operation against the domain api. This method is doing the
 * real work by talking to the remote server and sending JSON data, that
 * is obtained by serializing the operation.
 *
 * Please do not use this API , but execute()
 * @return JsonNode that describes the result
 * @param operation an Operation that should be run on the domain controller
 * @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation)
 * @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation, boolean)
 * @see #executeComplex(org.rhq.modules.plugins.jbossas7.json.Operation)
 *//*  w w  w . j  av a 2 s. c o m*/
public JsonNode executeRaw(Operation operation) {

    InputStream inputStream = null;
    BufferedReader br = null;
    InputStream es = null;
    HttpURLConnection conn = null;
    long t1 = System.currentTimeMillis();
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/json");
        conn.addRequestProperty("Accept", "application/json");
        conn.setConnectTimeout(10 * 1000); // 10s
        conn.setReadTimeout(10 * 1000); // 10s

        if (conn.getReadTimeout() != 10 * 1000)
            log.warn("JRE uses a broken timeout mechanism - nothing we can do");

        OutputStream out = conn.getOutputStream();

        String json_to_send = mapper.writeValueAsString(operation);

        //check for spaces in the path which the AS7 server will reject. Log verbose error and
        // generate failure indicator.
        if ((operation != null) && (operation.getAddress() != null)
                && operation.getAddress().getPath() != null) {
            if (containsSpaces(operation.getAddress().getPath())) {
                Result noResult = new Result();
                String outcome = "- Path '" + operation.getAddress().getPath()
                        + "' in invalid as it cannot contain spaces -";
                if (verbose) {
                    log.error(outcome);
                }
                noResult.setFailureDescription(outcome);
                noResult.setOutcome("failure");
                JsonNode invalidPathResult = mapper.valueToTree(noResult);
                return invalidPathResult;
            }
        }

        if (verbose) {
            log.info("Json to send: " + json_to_send);
        }

        mapper.writeValue(out, operation);

        out.flush();
        out.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }

        if (inputStream != null) {

            br = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }

            String outcome;
            JsonNode operationResult;
            if (builder.length() > 0) {
                outcome = builder.toString();
                operationResult = mapper.readTree(outcome);
                if (verbose) {
                    ObjectMapper om2 = new ObjectMapper();
                    om2.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
                    String tmp = om2.writeValueAsString(operationResult);
                    log.info(tmp);
                }
            } else {
                outcome = "- no response from server -";
                Result noResult = new Result();
                noResult.setFailureDescription(outcome);
                noResult.setOutcome("failure");
                operationResult = mapper.valueToTree(noResult);
            }
            return operationResult;
        } else {
            //if not properly authorized sends plugin exception for visual indicator in the ui.
            if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED
                    || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
                if (log.isDebugEnabled()) {
                    log.debug("[" + url + "] Response was empty and response code was " + responseCode + " "
                            + conn.getResponseMessage() + ".");
                }
                throw new InvalidPluginConfigurationException(
                        "Credentials for plugin to connect to AS7 management interface are invalid. Update Connection Settings with valid credentials.");
            } else {
                log.error("[" + url + "] Response was empty and response code was " + responseCode + " "
                        + conn.getResponseMessage() + ".");
            }
        }
    } catch (IllegalArgumentException iae) {
        log.error("Illegal argument " + iae);
        log.error("  for input " + operation);
    } catch (SocketTimeoutException ste) {
        log.error("Request to AS timed out " + ste.getMessage());
        conn.disconnect();
        Result failure = new Result();
        failure.setFailureDescription(ste.getMessage());
        failure.setOutcome("failure");
        failure.setRhqThrowable(ste);

        JsonNode ret = mapper.valueToTree(failure);
        return ret;

    } catch (IOException e) {
        log.error("Failed to get data: " + e.getMessage());

        //the following code is in place to help keep-alive http connection re-use to occur.
        if (conn != null) {//on error conditions it's still necessary to read the response so JDK knows can reuse
            //the http connections behind the scenes.
            es = conn.getErrorStream();
            if (es != null) {
                BufferedReader dr = new BufferedReader(new InputStreamReader(es));
                String ignore = null;
                try {
                    while ((ignore = dr.readLine()) != null) {
                        //already reported error. just empty stream.
                    }
                    es.close();
                } catch (IOException e1) {
                    // ignore
                }
            }
        }

        Result failure = new Result();
        failure.setFailureDescription(e.getMessage());
        failure.setOutcome("failure");
        failure.setRhqThrowable(e);

        JsonNode ret = mapper.valueToTree(failure);
        return ret;

    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (es != null) {
            try {
                es.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        long t2 = System.currentTimeMillis();
        PluginStats stats = PluginStats.getInstance();
        stats.incrementRequestCount();
        stats.addRequestTime(t2 - t1);
    }

    return null;
}

From source file:export.MapMyRunUploader.java

@Override
public Status connect() {
    if (isConfigured()) {
        return Status.OK;
    }//from  w  ww . j  ava  2 s  .c o m

    Status s = Status.NEED_AUTH;
    s.authMethod = Uploader.AuthMethod.USER_PASS;
    if (username == null || password == null) {
        return s;
    }

    Exception ex = null;
    HttpURLConnection conn = null;
    try {
        String pass = md5pass;
        if (pass == null) {
            pass = toHexString(Encryption.md5(password));
        }

        /**
         * get user id/key
         */
        conn = (HttpURLConnection) new URL(GET_USER_URL).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        FormValues kv = new FormValues();
        kv.put("consumer_key", CONSUMER_KEY);
        kv.put("u", username);
        kv.put("p", pass);

        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();

            InputStream in = new BufferedInputStream(conn.getInputStream());
            JSONObject obj = parse(in);
            conn.disconnect();

            try {
                JSONObject user = obj.getJSONObject("result").getJSONObject("output").getJSONObject("user");
                user_id = user.getString("user_id");
                user_key = user.getString("user_key");
                md5pass = pass;
                return Uploader.Status.OK;
            } catch (JSONException e) {
                System.err.println("obj: " + obj);
                throw e;
            }
        }
    } catch (MalformedURLException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    } catch (NoSuchAlgorithmException e) {
        ex = e;
    }

    if (conn != null)
        conn.disconnect();

    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}