Example usage for org.apache.http.client.methods HttpUriRequest addHeader

List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest addHeader.

Prototype

void addHeader(String str, String str2);

Source Link

Usage

From source file:org.onebusaway.gtfs_realtime.nextbus.services.DownloaderService.java

public synchronized InputStream openUrl(String uri) throws IOException {

    stallIfNeeded();/*from   w  w  w.  j  av  a  2 s  .  c o  m*/

    HttpUriRequest request = new HttpGet(uri);
    request.addHeader("Accept-Encoding", "gzip");
    HttpResponse response = _client.execute(request);
    HttpEntity entity = response.getEntity();

    noteDownload(entity);

    InputStream in = entity.getContent();
    Header contentEncoding = response.getFirstHeader("Content-Encoding");
    if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
        in = new GZIPInputStream(in);
    }
    return in;
}

From source file:org.getwheat.harvest.library.RequestProcessor.java

private void addBasicAuthHeaders(final HttpUriRequest request, final UserCredentials credentials) {
    request.addHeader(KEY_AUTHORIZATION, VALUE_BASIC + credentials.getBase64Value());
    HttpProtocolParams.setUserAgent(request.getParams(), VALUE_USER_AGENT);
}

From source file:com.citypark.api.parser.XMLParser.java

protected InputStream getInputStream() throws IOException {
    try {//  ww w  .j  av  a 2 s. c o  m
        HttpUriRequest request = new HttpGet(feedUrl.toString());
        request.addHeader("Accept-Encoding", "gzip");
        //request.addHeader("encoding", "utf-8");
        final HttpResponse response = new DefaultHttpClient().execute(request);
        Header ce = response.getFirstHeader("Content-Encoding");
        String contentEncoding = null;

        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == 500) { //TODO currently return 500, after server fix replace with 401
            //re login
            LoginTask.login(null);
            return null;
        }

        HttpEntity entity = response.getEntity();
        InputStream instream = null;

        if (entity != null)
            instream = entity.getContent();

        if (ce != null) {
            contentEncoding = ce.getValue();
            if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }
        }

        return instream;
    } catch (IOException e) {
        Log.e(e.getMessage(), "XML parser - " + feedUrl);
        throw e;
    }
}

From source file:org.quizpoll.net.DocsHelper.java

/**
 * Adds GData API headers to the request
 *///  w  ww  .  ja v  a  2 s .  c  o m
private HttpUriRequest addHeaders(HttpUriRequest request, PrefType type) {
    request.addHeader("GData-Version", "3.0");
    request.addHeader("Authorization", "GoogleLogin auth=" + Preferences.getString(type, authActivity));
    request.addHeader("Content-Type", "application/atom+xml; charset=UTF-8");
    return request;
}

From source file:org.opensuse.android.HttpCoreRestClient.java

private Resource execute(HttpUriRequest m) {
    try {// ww w. ja v a  2 s  .c  om
        m.addHeader("Authorization", "Basic " + getEncodedCredentials());

        HttpResponse response = connect().execute(m);
        int status = response.getStatusLine().getStatusCode();
        Log.w("HTTP_STATUS", Integer.toString(status));
        //Log.i("HTTP_CONTENT", response.getEntity().getContent().);

        return (new Resource(status, response.getEntity().getContent()));
    } catch (Exception e) {
        throw new RuntimeException("Couldn't execute request:", e);
    }
}

From source file:com.florianmski.tracktoid.image.Fanart.java

private synchronized void loadData(URL url, Context c) {
    try {//from   w  w w.j a  v a  2 s  .  c  o  m
        HttpUriRequest request = new HttpGet(url.toString());
        request.addHeader("Accept-Encoding", "gzip");
        res = http.execute(request);
    } catch (IOException e) {
        Log.e("FanartParser", "Error loading data", e);
    }
    try {
        //using special encoding to reduce download time
        InputStream instream = res.getEntity().getContent();
        Header contentEncoding = res.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"))
            instream = new GZIPInputStream(instream);

        xr.parse(new InputSource(instream));
    } catch (Exception e) {
        Log.e("FanartParser", "Error parsing data", e);
    }
}

From source file:ai.eve.volley.stack.HttpClientStack.java

/**
 * Called before the request is executed using the underlying HttpClient.
 *
 * <p>Overwrite in subclasses to augment the request.</p>
 *///  w  w  w.  jav a2  s. c  o m
protected void onPrepareRequest(HttpUriRequest request) throws IOException {
    request.addHeader("Accept-Encoding", "gzip");
}

From source file:org.opennms.features.poller.remote.gwt.server.geocoding.NominatimGeocoder.java

/** {@inheritDoc} */
@Override/*from w  w w.  j  a  v a  2 s. co m*/
public GWTLatLng geocode(final String geolocation) throws GeocoderException {
    final HttpUriRequest method = new HttpGet(getUrl(geolocation));
    method.addHeader("User-Agent", "OpenNMS-MapquestGeocoder/1.0");
    if (m_referer != null) {
        method.addHeader("Referer", m_referer);
    }

    try {
        InputStream responseStream = m_httpClient.execute(method).getEntity().getContent();
        final ElementTree tree = ElementTree.fromStream(responseStream);
        if (tree == null) {
            throw new GeocoderException(
                    "an error occurred connecting to the Nominatim geocoding service (no XML tree was found)");
        }

        final List<ElementTree> places = tree.findAll("//place");
        if (places.size() > 1) {
            LOG.warn("more than one location returned for query: {}", geolocation);
        } else if (places.size() == 0) {
            throw new GeocoderException("Nominatim returned an OK status code, but no places");
        }
        final ElementTree place = places.get(0);

        Double latitude = Double.valueOf(place.getAttribute("lat"));
        Double longitude = Double.valueOf(place.getAttribute("lon"));
        return new GWTLatLng(latitude, longitude);
    } catch (GeocoderException e) {
        throw e;
    } catch (Throwable e) {
        throw new GeocoderException("unable to get lat/lng from Nominatim", e);
    }
}

From source file:net.adamcin.httpsig.http.apache4.Http4UtilTest.java

@Test
public void testAllHeaders() {
    TestBody.test(new HttpServerTestBody() {
        @Override//from w w  w .jav a 2  s .  co m
        protected void execute() throws Exception {

            List<String> headers = Arrays.asList(Constants.HEADER_REQUEST_TARGET, Constants.HEADER_DATE,
                    "x-test");

            setServlet(new AdminServlet(headers));

            KeyPair keyPair = KeyTestUtil.getKeyPairFromProperties("b2048", "id_rsa");

            DefaultKeychain provider = new DefaultKeychain();
            provider.add(new SSHKey(KeyFormat.SSH_RSA, keyPair));

            DefaultHttpClient client = new DefaultHttpClient();

            Http4Util.enableAuth(client, provider, getKeyId());

            HttpUriRequest badRequest = new HttpGet(getAbsoluteUrl(TEST_URL));
            HttpResponse badResponse = client.execute(badRequest);

            badResponse.getEntity().writeTo(new NullOutputStream());

            assertEquals("should return 401", 401, badResponse.getStatusLine().getStatusCode());

            HttpUriRequest goodRequest = new HttpGet(getAbsoluteUrl(TEST_URL));
            goodRequest.addHeader("x-test", "foo");
            HttpResponse goodResponse = client.execute(goodRequest);

            goodResponse.getEntity().writeTo(new NullOutputStream());
            assertEquals("should return 200", 200, goodResponse.getStatusLine().getStatusCode());
        }
    });
}

From source file:org.wso2.am.integration.tests.other.APIMANAGER3965TestCase.java

@Test(groups = { "wso2.am" }, description = "Sample API creation")
public void testAPICreationWithOutCorsConfiguration() throws Exception {
    apiRequest.setProvider(user.getUserName());
    apiPublisher.addAPI(apiRequest);//from  w w  w . jav  a  2 s .  c  om
    APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName, user.getUserName(),
            APILifeCycleState.PUBLISHED);
    apiPublisher.changeAPILifeCycleStatus(updateRequest);

    waitForAPIDeploymentSync(apiRequest.getProvider(), apiRequest.getName(), apiRequest.getVersion(),
            APIMIntegrationConstants.IS_API_EXISTS);
    String apiInvocationUrl = getAPIInvocationURLHttp(apiContext + "/1.0.0/customers/123");

    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpUriRequest option = new HttpOptions(apiInvocationUrl);
    option.addHeader("Origin", "http://localhost:9443");
    HttpResponse serviceResponse = httpclient.execute(option);
    String accessControlAllowOrigin = serviceResponse.getFirstHeader("Access-Control-Allow-Origin").getValue();
    String accessControlAllowHeaders = serviceResponse.getFirstHeader("Access-Control-Allow-Headers")
            .getValue();
    String accessControlAllowMethods = serviceResponse.getFirstHeader("Access-Control-Allow-Methods")
            .getValue();
    assertEquals(serviceResponse.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(),
            "Response code mismatched when api invocation");
    assertEquals(accessControlAllowOrigin, "*",
            "Access Control allow origin values get mismatched in option Call");
    assertEquals(accessControlAllowHeaders, "authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction",
            "Access Control allow Headers values get mismatched in option Call");
    assertTrue(accessControlAllowMethods.contains("GET") && accessControlAllowMethods.contains("POST")
            && !accessControlAllowMethods.contains("DELETE") && !accessControlAllowMethods.contains("PUT")
            && !accessControlAllowMethods.contains("PATCH"),
            "Access Control allow Method values get mismatched in option Call");
}