Example usage for org.apache.http.message BasicHttpResponse setEntity

List of usage examples for org.apache.http.message BasicHttpResponse setEntity

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpResponse setEntity.

Prototype

public void setEntity(HttpEntity httpEntity) 

Source Link

Usage

From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.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  ww  .  jav a  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:com.ksc.http.KscHttpClientTest.java

@SuppressWarnings({ "unchecked", "deprecation" })
@Test//  w  w  w.  ja  v  a 2 s.  co  m
public void testRetryIOExceptionFromHandler() throws Exception {
    final IOException exception = new IOException("BOOM");

    HttpResponseHandler<KscWebServiceResponse<Object>> handler = EasyMock.createMock(HttpResponseHandler.class);

    EasyMock.expect(handler.needsConnectionLeftOpen()).andReturn(false).anyTimes();

    EasyMock.expect(handler.handle(EasyMock.<HttpResponse>anyObject())).andThrow(exception).times(2);

    EasyMock.replay(handler);

    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(new byte[0]));

    BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("http", 1, 1), 200, "OK");
    response.setEntity(entity);

    EasyMock.reset(httpClient);

    EasyMock.expect(httpClient.getConnectionManager()).andReturn(null).anyTimes();

    EasyMock.expect(httpClient.execute(EasyMock.<HttpUriRequest>anyObject(), EasyMock.<HttpContext>anyObject()))
            .andReturn(response).times(2);

    EasyMock.replay(httpClient);

    ExecutionContext context = new ExecutionContext();

    Request<?> request = new DefaultRequest<Object>(null, "testsvc");
    request.setEndpoint(java.net.URI.create("http://testsvc.region.amazonaws.com"));
    request.setContent(new java.io.ByteArrayInputStream(new byte[0]));

    try {

        client.execute(request, handler, null, context);
        Assert.fail("No exception when request repeatedly fails!");

    } catch (KscClientException e) {
        Assert.assertSame(exception, e.getCause());
    }

    // Verify that we called execute 4 times.
    EasyMock.verify(httpClient);
}

From source file:nl.waisda.services.EuropeanaImportServiceTest.java

private HttpResponse mockOverviewHttpResponse(String imageUrl) throws UnsupportedEncodingException {
    BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new HttpVersion(100, 1), 200, null));
    response.setEntity(new StringEntity(
            "{\"apikey\":\"test\",\"action\":\"search.json\",\"success\":true,\"requestNumber\":3713,\"itemsCount\":1,\"totalResults\":1,"
                    + "\"items\":[{\n" + "  \"id\":\"/08614/6569D2A45FD1CD9ADFB0E5BA54A3BD79C9DAE0BC\",\n"
                    + "  \"provider\":[\"EFG - The European Film Gateway\"],\n"
                    + (imageUrl != null ? "  \"edmPreview\":[\"" + imageUrl + "\"],\n" : "")
                    + "  \"europeanaCompleteness\":0,\n" + "  \"year\":[\"1921\"],\n"
                    + "  \"rights\":[\"http://www.europeana.eu/rights/rr-f/\"],\n"
                    + "  \"title\":[\"Opening Staten Generaal 20-9-1921\",\n"
                    + "  \"Opening States General 20-9-1921\"],\n" + "  \"type\":\"VIDEO\",\n"
                    + "  \"link\":\"http://detail\",\n"
                    + "  \"guid\":\"http://preview.europeana.eu/portal/record/08614/6569D2A45FD1CD9ADFB0E5BA54A3BD79C9DAE0BC.html?utm_source=api&utm_medium=api&utm_campaign=XxxsEZoWj\",\n"
                    + "  \"dataProvider\":[\"eye Film Instituut Nederland\",\"eye Film Instituut Nederland\"]\n"
                    + "}]}\n"));

    return response;
}

From source file:com.vincestyling.netroid.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);
    }//from w w w  . j  a  va2  s .c  o  m
    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));
    }

    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);
    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.exoplatform.mobile.tests.ExoActivityTestUtils.java

/**
 * Creates a BasicHttpResponse to use in Robolectric.addHttpResponseRule() for the specified request.<br/>
 * Response details:<br/>//from   w  w  w.  ja v  a2s  .co  m
 * - HTTP 1.1 <br/>
 * - 200 OK <br/>
 * - a content (entity) corresponding to the specified request, e.g. REQ_SOCIAL_VERSION_LATEST -> {"version":"v1-alpha3"}
 * @param req the id of the request, e.g REQ_SOCIAL_VERSION_LATEST
 * @return the response that matches the request id
 */
public BasicHttpResponse getResponseOKForRequest(int req) {
    BasicHttpResponse resp = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    try {

        switch (req) {
        case REQ_SOCIAL_VERSION_LATEST:
            resp.setEntity(new StringEntity(RESP_SOCIAL_VERSION_LATEST));
            break;

        case REQ_SOCIAL_IDENTITY:
        case REQ_SOCIAL_IDENTITY_2:
            resp.setEntity(new StringEntity(RESP_SOCIAL_IDENTITY));
            break;

        case REQ_SOCIAL_NEWS:
            resp.setEntity(new StringEntity(RESP_SOCIAL_NEWS));
            break;

        case REQ_SOCIAL_ALL_UPDATES:
            resp.setEntity(new StringEntity(RESP_SOCIAL_ALL_UPDATES));
            break;

        case REQ_SOCIAL_MY_CONNECTIONS:
            resp.setEntity(new StringEntity(RESP_SOCIAL_MY_CONNECTIONS));
            break;

        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return resp;
}

From source file:common.net.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();

    stethoManager = new StethoURLConnectionManager(url);

    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/* w  ww . j av a 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);
    requestDecompression(connection);

    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());

    stethoManager.postConnect();

    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:nl.waisda.services.EuropeanaImportServiceTest.java

private HttpResponse mockDetailHttpResponse(String videoUrl, String webresourceVideoUrl)
        throws UnsupportedEncodingException {
    BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new HttpVersion(100, 1), 200, null));
    response.setEntity(new StringEntity(
            "{\"apikey\":\"XxxsEZoWj\",\"action\":\"record.json\",\"success\":true,\"statsDuration\":50,\"requestNumber\":3752,"
                    + "\"object\":{\"type\":\"VIDEO\",\"year\":[\"1919\"],"
                    + "\"title\":[\"Opening Staten Generaal 20-9-1921\"],"
                    + "\"about\":\"/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"proxies\":[{\"about\":\"/proxy/provider/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"dcCreator\":{\"def\":[\"Nederlands Instituut voor Beeld en Geluid (beheerder)\",\"Netherlands Institute for Sound and Vison (curator)\"]},"
                    + "\"dcDate\":{\"def\":[\"1919-01-01\"]},\"dcDescription\":{\"def\":[]},\"dcLanguage\":{\"def\":[\"nl\"]},"
                    + "\"dcPublisher\":{\"def\":[\"Nederlands Instituut voor Beeld en Geluid\",\"http://www.openbeelden.nl/users/beeldengeluid\"]},"
                    + "\"dcSource\":{\"def\":[\"ONTHULLINGSTA-HRE00007FDA\"]},"
                    + "\"dcSubject\":{\"def\":[\"standbeelden\",\"volkscultuur\",\"steden\",\"zwemmen\",\"trams\",\"onthullingen\",\"wedstrijden\",\"optochten\",\"menigte\",\"hotels\",\"musici\",\"roeiboten\",\"kransleggingen\"]},"
                    + "\"dcTitle\":{\"def\":[\"Opening Staten Generaal 20-9-1921\"]},"
                    + "\"dcType\":{\"def\":[\"Moving Image\"]},"
                    + "\"dctermsAlternative\":{\"def\":[\"\",\"\"]},"
                    + "\"dctermsExtent\":{\"def\":[\"PT10M57S\"]},"
                    + "\"proxyIn\":[\"/aggregation/provider/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\"],"
                    + "\"proxyFor\":\"/item/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmType\":\"VIDEO\",\"europeanaProxy\":false},"
                    + "{\"about\":\"/proxy/europeana/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmHasMet\":{\"def\":[\"http://semium.org/time/19xx_1_third\",\"http://semium.org/time/1919\"]},"
                    + "\"proxyIn\":[\"/aggregation/europeana/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\"],"
                    + "\"proxyFor\":\"/item/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"year\":{\"def\":[\"1919\"]}," + "\"europeanaProxy\":true}],"
                    + "\"aggregations\":[{\"about\":\"/aggregation/provider/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmDataProvider\":{\"def\":[\"Open Beelden\"]},"
                    + (videoUrl != null ? "\"edmIsShownBy\":\"" + videoUrl + "\"," : "")
                    + "\"edmIsShownAt\":\"http://preview.europeana.eu/api/728/redirect.json?shownAt=http%3A%2F%2Fwww.openbeelden.nl%2Fmedia%2F3969%3Fbt%3Deuropeanaapi&provider=Nationale+Aggregator&id=http://www.europeana.eu/resolve/record/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9&profile=full\","
                    + "\"edmObject\":\"http://www.openbeelden.nl/images/66690/Vlissingen_%285_28%29.png\","
                    + "\"edmProvider\":{\"def\":[\"Nationale Aggregator\"]},"
                    + "\"edmRights\":{\"def\":[\"http://creativecommons.org/licenses/by-sa/3.0/nl/\"]},"
                    + "\"webResources\":[{\"about\":\"http://www.openbeelden.nl/media/3969\"},"
                    + (webresourceVideoUrl != null ? "{\"about\":\"" + webresourceVideoUrl + "\"}," : "")
                    + "{\"about\":\"http://www.openbeelden.nl/images/66690/Vlissingen_%285_28%29.png\"}]}],"
                    + "\"timespans\":[{\"about\":\"http://semium.org/time/19xx_1_third\","
                    + "\"prefLabel\":{\"en\":[\"early 20th century\"],\"ru\":[\"\"]}},"
                    + "{\"about\":\"http://semium.org/time/1919\"," + "\"prefLabel\":{\"def\":[\"1919\"]},"
                    + "\"isPartOf\":{\"en\":[\"http://semium.org/time/19xx_1_third\"]}}],"
                    + "\"europeanaCompleteness\":10,"
                    + "\"providedCHOs\":[{\"about\":\"/item/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\"}],\"europeanaAggregation\":{\"about\":\"/aggregation/europeana/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmLandingPage\":\"http://www.europeana.eu/portal/record/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmCountry\":{\"def\":[\"netherlands\"]}," + "\"edmLanguage\":{\"def\":[\"nl\"]}},"
                    + "\"europeanaCollectionName\":[\"2021601_Ag_NL_DNA_Open_Beelden\"]}}"));

    return response;
}

From source file:com.gistlabs.mechanize.cache.inMemory.InMemoryCacheEntry.java

@Override
public HttpResponse head() {
    BasicHttpResponse response = new BasicHttpResponse(this.response.getStatusLine());
    Header[] allHeaders = this.response.getAllHeaders();
    for (Header allHeader : allHeaders)
        response.addHeader(allHeader);/*from w w w.  j  ava 2  s.  com*/
    response.setEntity(new ByteArrayEntity(new byte[] {}));
    return response;
}

From source file:com.yangcong345.android.phone.manager.OkHttpStack.java

@Override
public synchronized HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();

    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }/*from  w w  w. j a v a  2 s.c  o m*/
        url = rewritten;
    }

    /*init request builder*/
    okhttp3.Request.Builder okRequestBuilder = new okhttp3.Request.Builder().url(url)
            .cacheControl(new CacheControl.Builder().maxAge(0, TimeUnit.SECONDS).build());

    /*set request headers*/
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    for (String headerName : map.keySet()) {
        okRequestBuilder.addHeader(headerName, map.get(headerName));
    }

    /*set request method*/
    setRequestMethod(okRequestBuilder, request);

    okhttp3.Request okRequest = okRequestBuilder.build();

    /*init request client*/
    int timeoutMs = request.getTimeoutMs();
    OkHttpClient.Builder okClientBuilder = new OkHttpClient.Builder();
    okClientBuilder.followRedirects(HttpURLConnection.getFollowRedirects())
            .followSslRedirects(HttpURLConnection.getFollowRedirects())
            .connectTimeout(timeoutMs, TimeUnit.MILLISECONDS).readTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    if (okRequest.isHttps() && mSslSocketFactory != null) {
        okClientBuilder.sslSocketFactory(mSslSocketFactory);
    }

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);

    OkHttpClient okClient = okClientBuilder.build();

    Response okResponse = okClient.newCall(okRequest).execute();
    int responseCode = okResponse.code();
    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, responseCode, okResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromOkHttp(okResponse));
    }

    for (int i = 0; i < okResponse.headers().size(); i++) {
        String name = okResponse.headers().name(i);
        String value = okResponse.headers().value(i);
        Header h = new BasicHeader(name, value);
        response.addHeader(h);
    }
    return response;
}

From source file:cn.com.xxutils.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());// ww  w  . ja  v  a 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);
    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;
}