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

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

Introduction

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

Prototype

public BasicHttpResponse(StatusLine statusLine) 

Source Link

Usage

From source file:com.meh.nprutil.StreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*from  w ww. j a  va2s.c o  m*/
    }
    Log.d(LOG_TAG, "processing");
    String url = request.getRequestLine().getUri();
    HttpResponse realResponse = download(url);
    if (realResponse == null) {
        return;
    }

    Log.d(LOG_TAG, "downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(line);
    response.setHeaders(realResponse.getAllHeaders());

    Log.d(LOG_TAG, "reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());

    httpString.append("\r\n");
    for (Header h : response.getAllHeaders()) {
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\r\n");
    }
    httpString.append("\r\n");
    Log.d(LOG_TAG, "headers done");

    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes;
        Log.d(LOG_TAG, "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // Start streaming content.
        byte[] buff = new byte[1024 * 50];
        while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();
    }
}

From source file:com.meh.IceProxy1.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*  ww  w  . j  ava2  s . co m*/
    }
    Log.d(tag, "processing");
    String url = request.getRequestLine().getUri();
    HttpResponse realResponse = download(url);
    if (realResponse == null) {
        return;
    }

    Log.d(tag, "downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse dummyresponse = new BasicHttpResponse(line);
    dummyresponse.setHeaders(realResponse.getAllHeaders());

    Log.d(tag, "reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(dummyresponse.getStatusLine().toString());
    httpString.append("\r\n");

    int icyInterval = -1;
    for (Header h : dummyresponse.getAllHeaders()) {
        if (ICY_INTERVAL_HEADER.equals(h.getName()))
            icyInterval = Integer.parseInt(h.getValue());
        else
            httpString.append(h.getName()).append(": ").append(h.getValue()).append("\r\n");
    }
    httpString.append("\r\n");
    Log.d(tag, "headers done");

    try {
        byte[] buffer = new byte[1024 * 16];
        int totalReadBytes = 0; //not including metadata
        int readBytes;

        byte[] httpdata = httpString.toString().getBytes();
        client.getOutputStream().write(httpdata, 0, httpdata.length);

        //now start streaming
        int bytesSinceLastIcy = 0;
        while (isRunning && (readBytes = data.read(buffer, 0, buffer.length)) != -1) {

            totalReadBytes += readBytes;
            bytesSinceLastIcy += readBytes;
            if (icyInterval != -1 && bytesSinceLastIcy > icyInterval) {
                //the icy metadata is in the buffer\
                int metadataPos = readBytes - (bytesSinceLastIcy - icyInterval);
                client.getOutputStream().write(buffer, 0, metadataPos);
                int metadataLength = buffer[metadataPos] * 16;
                byte[] metadata = new byte[metadataLength];
                System.arraycopy(buffer, metadataPos + 1, metadata, 0, metadataLength);
                Log.v(tag, new String(metadata));
                int remainingStart = metadataPos + 1 + metadataLength;
                int remainingLen = readBytes - metadataPos - metadataLength - 1;
                client.getOutputStream().write(buffer, remainingStart, remainingLen);
                bytesSinceLastIcy = remainingLen;
            } else
                client.getOutputStream().write(buffer, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();
    }
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnectionTest.java

/**
 * Tests creation of a web response.//  w w w. j a  v a2s .  c  o m
 * @throws Exception if the test fails
 */
@Test
public void makeWebResponse() throws Exception {
    final URL url = new URL("http://htmlunit.sourceforge.net/");
    final String content = "<html><head></head><body></body></html>";
    final DownloadedContent downloadedContent = new DownloadedContent.InMemory(content.getBytes());
    final int httpStatus = HttpStatus.SC_OK;
    final long loadTime = 500L;

    final ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 0);
    final StatusLine statusLine = new BasicStatusLine(protocolVersion, HttpStatus.SC_OK, null);
    final HttpResponse httpResponse = new BasicHttpResponse(statusLine);

    final HttpEntity responseEntity = new StringEntity(content);
    httpResponse.setEntity(responseEntity);

    final HttpWebConnection connection = new HttpWebConnection(getWebClient());
    final Method method = connection.getClass().getDeclaredMethod("makeWebResponse", HttpResponse.class,
            WebRequest.class, DownloadedContent.class, long.class);
    method.setAccessible(true);
    final WebResponse response = (WebResponse) method.invoke(connection, httpResponse, new WebRequest(url),
            downloadedContent, new Long(loadTime));

    assertEquals(httpStatus, response.getStatusCode());
    assertEquals(url, response.getWebRequest().getUrl());
    assertEquals(loadTime, response.getLoadTime());
    assertEquals(content, response.getContentAsString());
    assertEquals(content.getBytes(), IOUtils.toByteArray(response.getContentAsStream()));
    assertEquals(new ByteArrayInputStream(content.getBytes()), response.getContentAsStream());
}

From source file:com.daidiansha.acarry.control.network.core.volley.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<String, String>();
    map.putAll(request.getHeaders());/*from www  .j av  a  2s .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 (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (request instanceof MultiPartRequest) {
        setConnectionParametersForMultipartRequest(connection, (MultiPartRequest) 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:org.callimachusproject.auth.DigestPasswordAccessor.java

public HttpResponse getPersistentLogin(String iri) throws OpenRDFException, IOException {
    DetachedRealm realm = realms.getRealm(iri);
    if (realm == null)
        return null;
    String secret = realm.getOriginSecret();
    String nonce = nextNonce();/*from   w w  w. ja  v a2 s  .c  o m*/
    BasicHttpResponse resp = new BasicHttpResponse(_200);
    resp.addHeader("Set-Cookie",
            digestNonce + nonce + ";Max-Age=" + THREE_MONTHS + ";Path=/;HttpOnly" + digestNonceSecure);
    resp.addHeader("Cache-Control", "private");
    resp.setHeader("Content-Type", "text/plain;charset=UTF-8");
    String hash = md5(nonce + ":" + secret);
    resp.setEntity(new StringEntity(hash, Charset.forName("UTF-8")));
    return resp;
}

From source file:org.sentilo.platform.server.test.parser.SubscribeParserTest.java

@Test
public void parseWriteResponse() throws Exception {
    final SentiloResponse response = SentiloResponse
            .build(new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_0, 200, "")));
    parser.writeResponse(response, getSubscriptions());
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ((ByteArrayEntity) response.getHttpResponse().getEntity()).writeTo(baos);
    final String expected = "{\"subscriptions\":[{\"endpoint\":\"htt://dev.connecta.cat\",\"type\":\"ALARM\",\"alert\":\"alarm1\"},{\"endpoint\":\"htt://dev.connecta.cat\",\"type\":\"ORDER\",\"provider\":\"prov2\"},{\"endpoint\":\"htt://dev.connecta.cat\",\"type\":\"DATA\",\"provider\":\"prov2\"},{\"endpoint\":\"htt://dev.connecta.cat\",\"type\":\"DATA\",\"provider\":\"prov2\",\"sensor\":\"sensor2\"}]}";
    assertEquals(expected, baos.toString());
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void test302() throws Exception {
    responses.add(new BasicHttpResponse(_302));
    client.execute(new HttpGet("http://example.com/302"), new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_302.getStatusCode(), response.getStatusLine().getStatusCode());
            return null;
        }/*from   ww  w.  java 2s .  co  m*/
    });
}

From source file:org.gbif.registry.metasync.protocols.digir.DigirMetadataSynchroniserTest.java

public HttpResponse prepareResponse(int responseStatus, String fileName) throws IOException {
    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), responseStatus, ""));
    response.setStatusCode(responseStatus);
    byte[] bytes = Resources.toByteArray(Resources.getResource(fileName));
    response.setEntity(new ByteArrayEntity(bytes));
    return response;
}

From source file:com.betfair.cougar.client.HttpClientExecutableTest.java

@Test
public void testFailingCall() throws IOException {
    generateEV(tsd, null);// w w  w .  j a  v a  2  s. c om
    HttpUriRequest mockMethod = mock(HttpUriRequest.class);
    final BasicHttpResponse httpResponse = new BasicHttpResponse(
            new BasicStatusLine(HttpVersion.HTTP_1_1, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ""));
    when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(httpResponse);
    when(mockMethodFactory.create(anyString(), anyString(), any(Message.class), any(Marshaller.class),
            anyString(), any(ClientCallContext.class), any(TimeConstraints.class))).thenReturn(mockMethod);
    when(mockedHttpErrorTransformer.convert(any(InputStream.class), any(ExceptionFactory.class), anyInt()))
            .thenReturn(new CougarClientException(ServerFaultCode.RemoteCougarCommunicationFailure, "bang"));

    HttpParams mockParams = mock(HttpParams.class);
    when(mockMethod.getParams()).thenReturn(mockParams);

    ExecutionObserver mockedObserver = mock(ExecutionObserver.class);
    client.execute(createEC(null, null, false), TestServiceDefinition.TEST_MIXED,
            new Object[] { TEST_TEXT, TEST_TEXT }, mockedObserver, ev, DefaultTimeConstraints.NO_CONSTRAINTS);

    ArgumentCaptor<ExecutionResult> resultCaptor = ArgumentCaptor.forClass(ExecutionResult.class);
    verify(mockedObserver).onResult(resultCaptor.capture());
    ExecutionResult actual = resultCaptor.getValue();
    assertEquals(ExecutionResult.ResultType.Fault, actual.getResultType());
    assertNotNull(actual.getFault());
    assertNull(actual.getResult());
    assertNull(actual.getSubscription());
    assertEquals(0, ((ClientExecutionResult) actual).getResultSize());
}

From source file:net.sf.jsog.client.DefaultJsogClientImplTest.java

@Test
public void testGet() throws Exception {

    String url = "http://www.example.com";
    JSOG expected = JSOG.object("foo", "bar");

    // Create and prepare the mock
    final HttpClient client = createMock(HttpClient.class);
    Capture<HttpGet> request = new Capture<HttpGet>();

    HttpResponse response = new BasicHttpResponse(createStatusLine(200, "OK"));
    response.setEntity(createStringEntity(expected));
    expect(client.execute(capture(request))).andReturn(response);

    // Create the instance
    DefaultJsogClientImpl instance = new DefaultJsogClientImpl() {
        @Override//  w w  w .  j a va2s. c  om
        protected HttpClient getClient() {
            return client;
        }
    };

    // Run the test
    replay(client);

    JSOG actual = instance.getJsog(url);
    assertEquals(expected, actual);

    verify(client);

    Header[] headers = request.getValue().getHeaders("Content-Type");
    assertEquals(0, headers.length);
}