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(ProtocolVersion protocolVersion, int i, String str) 

Source Link

Usage

From source file:com.navjagpal.fileshare.WebServer.java

/**
 * Sends a ZIP file containing all files from the shared folder.
 * //from  w  w w .jav a2  s.  co  m
 * @param serverConnection
 * @param requestLine
 * @throws IOException
 * @throws HttpException
 */
private void sendFolderContent(DefaultHttpServerConnection serverConnection, RequestLine requestLine)
        throws IOException, HttpException {
    HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 200, "OK");
    String folderId = getFolderId(requestLine.getUri());
    addFolderZipEntity(folderId, response);
    serverConnection.sendResponseHeader(response);
    serverConnection.sendResponseEntity(response);
}

From source file:com.navjagpal.fileshare.WebServer.java

private void sendPlaylist(DefaultHttpServerConnection serverConnection, RequestLine requestLine)
        throws IOException, HttpException {
    HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 200, "OK");

    Cursor c = mContext.getContentResolver().query(FileSharingProvider.Files.CONTENT_URI, new String[] {
            FileSharingProvider.Files.Columns._ID, FileSharingProvider.Files.Columns.DISPLAY_NAME }, null, null,
            null);/*from   w ww. j  ava  2  s  . co  m*/
    String playlist = "";
    while (c.moveToNext()) {
        long id = c.getLong(c.getColumnIndex(FileSharingProvider.Files.Columns._ID));
        String name = c.getString(c.getColumnIndex(FileSharingProvider.Files.Columns.DISPLAY_NAME));
        if (name.endsWith(".mp3")) {
            playlist += SharedFileBrowser.getShareURL(id, mContext) + "\n";
        }
    }
    c.close();
    response.addHeader("Content-Type", "audio/x-mpegurl");
    response.addHeader("Content-Length", "" + playlist.length());
    response.setEntity(new StringEntity(playlist));
    serverConnection.sendResponseHeader(response);
    serverConnection.sendResponseEntity(response);
}

From source file:org.esigate.DriverTest.java

/**
 * 0000174: Redirect location with default port specified are incorrectly rewritten when preserveHost=true
 * <p>// ww w  . j  a va 2s.  co  m
 * http://www.esigate.org/mantisbt/view.php?id=174
 * 
 * <p>
 * Issue with default ports, which results in invalid url creation.
 * 
 * @throws Exception
 */
public void testRewriteRedirectResponseWithDefaultPortSpecifiedInLocation() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE, "http://www.foo.com:8080");
    properties.put(Parameters.PRESERVE_HOST, "true");
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_MOVED_TEMPORARILY, "Found");
    // The backend server sets the port even if default (OK it should not
    // but some servers do it)
    response.addHeader("Location", "http://www.foo.com:80/foo/bar");
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    request = TestUtils.createIncomingRequest("http://www.foo.com:80/foo");
    // HttpClientHelper will use the Host
    // header to rewrite the request sent to the backend
    // http://www.foo.com/foo
    CloseableHttpResponse driverResponse = driver.proxy("/foo", request.build());
    // The test initially failed with an invalid Location:
    // http://www.foo.com:80:80/foo/bar
    assertEquals("http://www.foo.com:80/foo/bar", driverResponse.getFirstHeader("Location").getValue());
}

From source file:name.persistent.behaviours.PURLSupport.java

private HttpResponse prepareResponse(HttpResponse resp, String linkHeader, Set<String> via) throws IOException {
    if (resp.containsHeader("Content-Location")) {
        String url = resp.getFirstHeader("Content-Location").getValue();
        HttpResponse bd = getFinalResponse(url, via);
        int code = bd.getStatusLine().getStatusCode();
        if (code == 200 || code == 203) {
            for (Header hd : bd.getAllHeaders()) {
                resp.removeHeaders(hd.getName());
            }// ww w .j  a  va2 s  . c  o m
            resp.setHeader("Link", linkHeader);
            for (Header hd : bd.getAllHeaders()) {
                resp.addHeader(hd);
            }
            resp.setEntity(bd.getEntity());
            if (!resp.containsHeader("Last-Modified") && resp.containsHeader("Date")) {
                String date = resp.getFirstHeader("Date").getValue();
                resp.setHeader("Last-Modified", date);
            }
        } else {
            HttpEntity entity = bd.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
            String msg = bd.getStatusLine().getReasonPhrase();
            return new BasicHttpResponse(HTTP11, 502, msg);
        }
    } else {
        resp.setHeader("Link", linkHeader);
        purlSetEntityHeaders(resp);
    }
    return resp;
}

From source file:org.opendatakit.http.conn.GaeManagedClientConnection.java

@Override
public HttpResponse receiveResponseHeader() throws HttpException, IOException {
    if (response == null) {
        throw new IllegalStateException("no response avaliable");
    }// w ww.  j a v  a 2s  . co m
    // we don't have access to the protocol version, so assume it is Http 1.1
    HttpResponse resp = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), response.getResponseCode(),
            null);

    for (com.google.appengine.api.urlfetch.HTTPHeader h : response.getHeaders()) {
        resp.addHeader(new BasicHeader(h.getName(), h.getValue()));
    }

    return resp;
}

From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java

private HttpResponse requestPOST(WfsOperation operation)
        throws ParserConfigurationException, TransformerException, IOException, SAXException {

    URI url = findUrl(operation.getOperation(), WFS.METHOD.POST);

    HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient;

    URIBuilder uri = new URIBuilder(url);

    String xml = operation.asXml(new XMLDocumentFactory(nsStore), versions).toString(false);

    LOGGER.debug("{}\n{}", uri, xml);

    HttpPost httpPost;/*from w  w w  .ja v a 2 s  .com*/
    HttpResponse response = null;

    try {
        httpPost = new HttpPost(uri.build());

        /*for( String key : operation.getRequestHeaders().keySet()) {
        httpPost.setHeader(key, operation.getRequestHeaders().get(key));
        }*/

        // TODO: temporary basic auth hack
        if (useBasicAuth) {
            httpPost.addHeader("Authorization", "Basic " + basicAuthCredentials);
        }

        StringEntity xmlEntity = new StringEntity(xml, ContentType.create("text/plain", "UTF-8"));
        httpPost.setEntity(xmlEntity);

        response = httpClient.execute(httpPost, new BasicHttpContext());

        // check http status
        checkResponseStatus(response.getStatusLine().getStatusCode(), uri);

    } catch (SocketTimeoutException ex) {
        if (ignoreTimeouts) {
            LOGGER.warn("POST request timed out after %d ms, URL: {} \\nRequest: {}",
                    HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri, xml);
        }
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "");
        response.setEntity(new StringEntity("", ContentType.TEXT_XML));
    } catch (IOException ex) {
        //LOGGER.error(ERROR_IN_POST_REQUEST_TO_URL_REQUEST, uri.toString(), xml, ex);
        //LOGGER.debug("Error requesting URL: {}", uri.toString());

        try {
            if (!isDefaultUrl(uri.build(), WFS.METHOD.POST)) {

                LOGGER.info("Removing URL: {}", uri);
                this.urls.remove(operation.getOperation().toString());

                LOGGER.info("Retry with default URL: {}", this.urls.get("default"));
                return requestPOST(operation);
            }
        } catch (URISyntaxException ex0) {
        }

        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (URISyntaxException ex) {
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (ReadError ex) {
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw ex;
    }
    LOGGER.debug("WFS request submitted");
    return response;
}

From source file:ut.ee.mh.WebServer.java

/**
 * Added by Carlos//from w  ww  . j  av  a  2  s.co m
 * 
 * @param serverConnection
 * @param request
 * @param requestLine
 * @throws IOException
 * @throws HttpException
 * @throws UnsupportedEncodingException
 */
private void handlePostRequest(DefaultHttpServerConnection serverConnection, HttpRequest request,
        RequestLine requestLine) throws IOException, HttpException, UnsupportedEncodingException {
    HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 200, "OK");
    String folderId = getFolderId(requestLine.getUri());
    processUpload(folderId, request, serverConnection);
    String header = getHTMLHeader();
    String form = getUploadForm(folderId);
    String footer = getHTMLFooter();
    String listing = getFileListing(Uri.withAppendedPath(FileSharingProvider.Folders.CONTENT_URI, folderId));
    response.setEntity(new StringEntity(header + listing + form + footer));
    serverConnection.sendResponseHeader(response);
    serverConnection.sendResponseEntity(response);
}

From source file:com.navjagpal.fileshare.WebServer.java

private void sendSharedFilesList(DefaultHttpServerConnection serverConnection, RequestLine requestLine)
        throws UnsupportedEncodingException, HttpException, IOException {
    HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 200, "OK");
    String folderId = getFolderId(requestLine.getUri());
    String header = getHTMLHeader();
    String form = getUploadForm(folderId);
    String footer = getHTMLFooter();
    String listing = getFileListing(Uri.withAppendedPath(FileSharingProvider.Folders.CONTENT_URI, folderId));
    response.setEntity(new StringEntity(header + listing + form + footer));
    serverConnection.sendResponseHeader(response);
    serverConnection.sendResponseEntity(response);
}

From source file:com.flipkart.poseidon.handlers.http.impl.SinglePoolHttpTaskHandler.java

private HttpResponse getDummyHttpResponse(int statusCode) {
    HttpResponse response = null;/*ww  w .  j  ava  2  s  .com*/
    switch (statusCode) {
    case HttpStatus.SC_OK:
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
        break;
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR,
                "Internal Server Error");
        break;
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_SERVICE_UNAVAILABLE,
                "Service Unavailable");
        break;
    default:
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "Bad Request");
        break;
    }
    return response;
}