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.kubeiwu.commontool.khttp.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());//
    map.putAll(additionalHeaders);// www. j  av a 2  s  . c o m
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);// ?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()) {// header
        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);
            //cookie?
            String key = header.getKey();
            List<String> values = header.getValue();
            if (key.equalsIgnoreCase("set-cookie")) {
                StringBuilder cookieString = new StringBuilder();
                for (String value : values) {
                    cookieString.append(value).append("\n");// \ncookie??
                }
                cookieString.deleteCharAt(cookieString.length() - 1);
                Header h = new BasicHeader(header.getKey(), cookieString.toString());
                response.addHeader(h);
            } else {
                Header h = new BasicHeader(header.getKey(), values.get(0));
                response.addHeader(h);
            }
        }
    }
    System.out.println("performRequest---999999-getStatusLine=" + response.getStatusLine());
    return response;
}

From source file:com.miya38.connection.volley.CustomHurlStack.java

@Override
public HttpResponse performRequest(final Request<?> request, final Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    final HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from ww  w . jav  a  2  s  . co m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        final String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    final URL parsedUrl = new URL(url);
    final HttpURLConnection connection = openConnection(parsedUrl, request);
    for (final String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    final ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    final 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.");
    }
    final StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    final BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (final Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            // bug fix y-miyazaki start
            for (final String value : header.getValue()) {
                final Header h = new BasicHeader(header.getKey(), value);
                response.addHeader(h);
            }
            // bug fix y-miyazaki end
        }
    }
    return response;
}

From source file:com.autonavi.gxdtaojin.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 ww  . j a 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 = null;
    try {
        parsedUrl = new URL(url);
    } catch (Throwable t) {
        t.printStackTrace();
        parsedUrl = new URL("http://www.google.com");
    }
    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.vimc.ahttp.HurlWorker.java

@Override
public HttpResponse doHttpRquest(Request<?> request) throws IOException {
    String url = request.getUrl();

    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }//from  www  .  j  a v  a 2s . c  o m
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    addHeadersIfExists(request, connection);
    setConnectionParametersByRequest(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.gooddata.http.client.LoginSSTRetrievalStrategyTest.java

@Test
public void shouldLogout() throws Exception {
    statusLine = new BasicStatusLine(new ProtocolVersion("https", 1, 1), HttpStatus.SC_NO_CONTENT,
            "NO CONTENT");
    final HttpResponse response = new BasicHttpResponse(statusLine);
    when(httpClient.execute(isA(HttpHost.class), isA(HttpDelete.class))).thenReturn(response);

    sstStrategy.logout(httpClient, host, "/gdc/account/login/profileid", SST, TT);

    final ArgumentCaptor<HttpHost> hostCaptor = ArgumentCaptor.forClass(HttpHost.class);
    final ArgumentCaptor<HttpDelete> deleteCaptor = ArgumentCaptor.forClass(HttpDelete.class);

    verify(httpClient).execute(hostCaptor.capture(), deleteCaptor.capture());

    assertEquals("server.com", hostCaptor.getValue().getHostName());
    assertEquals(123, hostCaptor.getValue().getPort());

    final HttpDelete delete = deleteCaptor.getValue();
    assertNotNull(delete);/*  w w w  .j  a v  a  2 s  .  c  om*/
    assertEquals("/gdc/account/login/profileid", delete.getURI().getPath());
    assertEquals(SST, delete.getFirstHeader("X-GDC-AuthSST").getValue());
    assertEquals(TT, delete.getFirstHeader("X-GDC-AuthTT").getValue());
}

From source file:org.peterbaldwin.vlcremote.sweep.Worker.java

@Override
public void run() {
    // Note: InetAddress#isReachable(int) always returns false for Windows
    // hosts because applications do not have permission to perform ICMP
    // echo requests.
    for (;;) {/*from   w  ww  . ja va2 s.  co m*/
        byte[] ipAddress = mManager.pollIpAddress();
        if (ipAddress == null) {
            break;
        }
        try {
            InetAddress address = InetAddress.getByAddress(ipAddress);
            String hostAddress = address.getHostAddress();
            URL url = createUrl("http", hostAddress, mPort, mPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            try {
                int responseCode = connection.getResponseCode();
                String responseMessage = connection.getResponseMessage();
                InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK)
                        ? connection.getInputStream()
                        : connection.getErrorStream();
                if (inputStream != null) {
                    try {
                        int length = connection.getContentLength();
                        InputStreamEntity entity = new InputStreamEntity(inputStream, length);
                        entity.setContentType(connection.getContentType());

                        // Copy the entire response body into memory
                        // before the HTTP connection is closed:
                        String body = EntityUtils.toString(entity);

                        ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1);
                        String hostname = address.getHostName();
                        StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage);
                        HttpResponse response = new BasicHttpResponse(statusLine);
                        response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort);
                        response.setEntity(new StringEntity(body));
                        mCallback.onReachable(ipAddress, response);
                    } finally {
                        inputStream.close();
                    }
                } else {
                    Log.w(TAG, "InputStream is null");
                }
            } finally {
                connection.disconnect();
            }
        } catch (IOException e) {
            mCallback.onUnreachable(ipAddress, e);
        }
    }
}

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  va 2s  . c  o  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:com.google.android.apps.iosched.io.StubHttpClient.java

/**
 * Build a stub {@link HttpResponse}, probably for use with
 * {@link #setResponse(HttpResponse)}.//w w w. j  a  va 2  s .co  m
 *
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single
 *            {@link HttpEntity} to be included in the response, loaded
 *            through {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode, String assetName, Context context) throws IOException {
    final StatusLine status = new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, null);
    final HttpResponse response = new BasicHttpResponse(status);
    if (assetName != null) {
        final InputStream entity = context.getAssets().open(assetName);
        response.setEntity(new InputStreamEntity(entity, entity.available()));
    }
    return response;
}

From source file:cn.garymb.wechatmoments.common.OkHttpStack.java

@Override
@SuppressWarnings("deprecation")
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<>();
    map.putAll(request.getHeaders());/*from w  w w .ja v  a  2s. 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);
    OkUrlFactory okFactory = new OkUrlFactory(mClient);
    HttpURLConnection connection = openOkHttpURLConnection(okFactory, 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.nexmo.client.voice.endpoints.CreateCallMethodTest.java

@Test
public void testParseResponse() throws Exception {
    HttpWrapper wrapper = new HttpWrapper();
    CreateCallMethod methodUnderTest = new CreateCallMethod(wrapper);

    HttpResponse stubResponse = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("1.1", 1, 1), 200, "OK"));

    String json = " {\"uuid\":\"93137ee3-580e-45f7-a61a-e0b5716000ea\",\"status\":\"started\",\"direction\":\"outbound\",\"conversation_uuid\":\"aa17bd11-c895-4225-840d-30dc78c31e50\"}";
    InputStream jsonStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(jsonStream);//from ww w. j a  v a  2 s  .c  o m
    stubResponse.setEntity(entity);

    // Execute test call:
    CallEvent callEvent = methodUnderTest.parseResponse(stubResponse);
    assertEquals("93137ee3-580e-45f7-a61a-e0b5716000ea", callEvent.getUuid());
    assertEquals("aa17bd11-c895-4225-840d-30dc78c31e50", callEvent.getConversationUuid());
    assertEquals(CallStatus.STARTED, callEvent.getStatus());
    assertEquals(CallDirection.OUTBOUND, callEvent.getDirection());
}