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:com.cloudera.nav.sdk.examples.lineage3.LineageExport.java

private HttpURLConnection createHttpConnection(ClientConfig config, Set<String> entityIds) throws IOException {
    String navUrl = config.getNavigatorUrl();
    String serverUrl = navUrl + (navUrl.endsWith("/") ? LINEAGE_EXPORT_API : "/" + LINEAGE_EXPORT_API);
    String queryParamString = String.format(LINEAGE_EXPORT_API_QUERY_PARAMS,
            URLEncoder.encode(direction, charset), // direction of lineage
            URLEncoder.encode(length, charset), // length of lineage
            URLEncoder.encode(lineageOptions, charset)); // Apply all filters

    URL url = new URL(serverUrl + queryParamString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    String userpass = config.getUsername() + ":" + config.getPassword();
    String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    conn.addRequestProperty("Authorization", basicAuth);
    conn.addRequestProperty("Content-Type", "application/json");
    conn.addRequestProperty("Accept", "application/json");
    conn.setReadTimeout(0);//w  ww .j  a v  a  2  s.  com
    conn.setRequestMethod("POST");

    // entityIds to pass in the request body
    String postData = constructEntityIdsAsCSV(entityIds);
    postData = "[" + postData + "]";
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");
    conn.addRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    return conn;
}

From source file:org.codehaus.httpcache4j.urlconnection.URLConnectionResponseResolver.java

private void doRequest(HTTPRequest request, HttpURLConnection connection) throws IOException {
    configureConnection(connection);//w ww .jav a2  s.c o  m
    connection.setRequestMethod(request.getMethod().getMethod());
    Headers requestHeaders = request.getAllHeaders();

    for (Header header : requestHeaders) {
        connection.addRequestProperty(header.getName(), header.getValue());
    }
    connection.connect();
    writeRequest(request, connection);
}

From source file:org.deafsapps.sordomartinezpabloluismarspics.util.MarsPicsApiParser.java

@Override
public @Nullable MatrixCursor loadInBackground() {
    try {/* w  w  w  . jav a2s .c  o m*/
        /*
         * Construct the URL for the NASA Open API (NOA) query
         * Possible parameters are available at NOA's page
         * https://api.nasa.gov/index.html#getting-started
         */
        final String NASA_API_BASE_URL = "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?";
        final String NUMBER_ITEMS = "sol";
        final String API_KEY = "api_key";

        Uri builtUri = Uri.parse(NASA_API_BASE_URL).buildUpon().appendQueryParameter(NUMBER_ITEMS, "10")
                .appendQueryParameter(API_KEY, getContext().getString(R.string.NASA_OPEN_API_KEY)).build();

        URL url = new URL(builtUri.toString()); // Throws 'MalformedURLException'

        HttpURLConnection myConnection = (HttpURLConnection) url.openConnection(); // Throws 'IOException'
        myConnection.setRequestMethod("GET");
        myConnection.setConnectTimeout(HTTP_TIMEOUT_MILLIS);
        myConnection.addRequestProperty("Content-type", "application/json");

        int respCode = myConnection.getResponseCode(); // Throws 'IOException'
        if (BuildConfig.DEBUG) {
            Log.d(TAG_MARS_PICS_API_PARSER, "The response is: " + respCode);
        }

        if (respCode == HttpURLConnection.HTTP_OK) {
            StringBuilder resultJsonString = new StringBuilder();

            InputStream myInStream = myConnection.getInputStream(); // Throws 'IOException'
            BufferedReader myBufferedReader = new BufferedReader(new InputStreamReader(myInStream));

            String line;
            while ((line = myBufferedReader.readLine()) != null) {
                resultJsonString.append(line).append("\n");
            }
            myInStream.close(); // Always close the 'InputStream'
            myConnection.disconnect();

            return parseJsonString(resultJsonString.toString());
        }
    } catch (java.net.SocketTimeoutException e) {
        return null;
    } catch (java.io.IOException e) {
        return null;
    }

    return null;
}

From source file:com.event.app.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    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);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    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:ai.eve.volley.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }//ww w .j a  v  a2 s.co m
    if (!TextUtils.isEmpty(mSignInfo)) {
        map.put("SIGN", ESecurity.Encrypt(mSignInfo));
    }
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (EApplication.getCookies() != null) {
        ELog.I("cookie", EApplication.getCookies().toString());
        connection.addRequestProperty("Cookie", EApplication.getReqCookies());
    } else {
        ELog.I("cookie", "null");
    }
    setConnectionParametersForRequest(connection, request);
    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(new ProtocolVersion("HTTP", 1, 1),
            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) {
            if (header.getKey().equalsIgnoreCase("Set-Cookie")) {
                List<String> cookies = header.getValue();
                HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>();
                for (String string : cookies) {
                    List<HttpCookie> cookie = HttpCookie.parse(string);
                    for (HttpCookie httpCookie : cookie) {
                        if (httpCookie.getDomain() != null && httpCookie.getPath() != null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getDomain() + httpCookie.getPath(),
                                    httpCookie);
                        } else if (httpCookie.getDomain() == null && httpCookie.getPath() != null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getPath(), httpCookie);
                        } else if (httpCookie.getDomain() != null && httpCookie.getPath() == null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getDomain(), httpCookie);
                        } else {
                            cookieMap.put(httpCookie.getName(), httpCookie);
                        }
                    }
                }

                EApplication.setCookies(cookieMap);
                if (EApplication.getCookies() != null) {
                    ELog.I("?cookie", EApplication.getCookies().toString());
                }
            } else {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
    }

    return response;
}

From source file:org.openecomp.sdnc.sli.resource.mdsal.RestService.java

private HttpURLConnection getRestConnection(String urlString, String method) throws IOException {

    URL sdncUrl = new URL(urlString);
    Authenticator.setDefault(new SdncAuthenticator(user, passwd));

    HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection();

    String authStr = user + ":" + passwd;
    String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes()));

    conn.addRequestProperty("Authentication", "Basic " + encodedAuthStr);

    conn.setRequestMethod(method);//from w  ww  . j av a2  s.c  o  m

    if (payloadType == PayloadType.XML) {
        conn.setRequestProperty("Content-Type", "application/xml");
        conn.setRequestProperty("Accept", "application/xml");
    } else {

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
    }

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    return (conn);

}

From source file:com.yaozu.object.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//w w  w .jav  a  2 s . c om
    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);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    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);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        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:org.droidparts.net.http.RESTClient.java

public HTTPResponse get(String uri, long ifModifiedSince, String etag, boolean body) throws HTTPException {
    L.i("GET on '%s', If-Modified-Since: '%d', ETag: '%s', body: '%b'.", uri, ifModifiedSince, etag, body);
    HTTPResponse response;/*www .  j a  v a2 s  .  c o  m*/
    if (useHttpURLConnection()) {
        HttpURLConnection conn = httpURLConnectionWorker.getConnection(uri, Method.GET);
        if (ifModifiedSince > 0) {
            conn.setIfModifiedSince(ifModifiedSince);
        }
        if (etag != null) {
            conn.addRequestProperty(Header.IF_NONE_MATCH, etag);
        }
        response = HttpURLConnectionWorker.getReponse(conn, body);
    } else {
        HttpGet req = new HttpGet(uri);
        if (ifModifiedSince > 0) {
            req.addHeader(Header.IF_MODIFIED_SINCE, new Date(ifModifiedSince).toGMTString());
        }
        if (etag != null) {
            req.addHeader(Header.IF_NONE_MATCH, etag);
        }
        response = httpClientWorker.getReponse(req, body);
    }
    L.d(response);
    return response;
}

From source file:com.selene.volley.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    //      if (!TextUtils.isEmpty(mUserAgent)) {
    //         map.put(HTTP.USER_AGENT, mUserAgent);
    //      }//from w  w w  .  j a  v a  2s . co  m
    map.putAll(request.getHeaders());
    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);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    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);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        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:at.florian_lentsch.expirysync.net.JsonCaller.java

/**
 * Calls a server path and returns a json object with the server's response
 * @param path the url to call//from  w w  w. ja v a2 s .co m
 * @param method either {@code "GET"} or {@code "POST"}
 * @param params parameters to send to the server
 * @return the server's response
 * @throws MalformedURLException if the url is invalid
 * @throws IOException something went wrong while talking to the server
 * @throws ProtocolException if an invalid {@code method} has been passed
 * @throws JSONException invalid response received from the server
 */
public JSONObject performJsonCall(String path, String method, JSONObject params)
        throws MalformedURLException, IOException, ProtocolException, JSONException {

    String getParams = "";
    if (params != null && method == METHOD_GET) {
        getParams = jsonToGetParams(params);
    }

    URL url = new URL(this.host.toString() + path + getParams);
    boolean outputAvailable = (params != null && method != METHOD_GET);

    //connect to the server:
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    prepareConnection(connection, method, outputAvailable);
    connection.addRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
    connection.connect();

    // write out:
    if (outputAvailable) { // in case there are params and this is a POST request:
        writeParams(connection, params);
    }

    // read:
    determineTimeSkew(connection);
    storeCookies(connection);
    JSONObject obj = readJSON(connection);

    return obj;
}