Example usage for org.apache.http.client HttpResponseException HttpResponseException

List of usage examples for org.apache.http.client HttpResponseException HttpResponseException

Introduction

In this page you can find the example usage for org.apache.http.client HttpResponseException HttpResponseException.

Prototype

public HttpResponseException(final int statusCode, final String s) 

Source Link

Usage

From source file:interoperabilite.webservice.fluent.FluentResponseHandling.java

public static void main(String[] args) throws Exception {
    Document result = Request.Get("http://somehost/content").execute()
            .handleResponse(new ResponseHandler<Document>() {

                @Override//from w w w .j ava2  s. co m
                public Document handleResponse(final HttpResponse response) throws IOException {
                    StatusLine statusLine = response.getStatusLine();
                    HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                    try {
                        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                        ContentType contentType = ContentType.getOrDefault(entity);
                        if (!contentType.equals(ContentType.APPLICATION_XML)) {
                            throw new ClientProtocolException("Unexpected content type:" + contentType);
                        }
                        Charset charset = contentType.getCharset();
                        if (charset == null) {
                            charset = Consts.ISO_8859_1;
                        }
                        return docBuilder.parse(entity.getContent(), charset.name());
                    } catch (ParserConfigurationException ex) {
                        throw new IllegalStateException(ex);
                    } catch (SAXException ex) {
                        throw new ClientProtocolException("Malformed XML document", ex);
                    }
                }

            });
    // Do something useful with the result
    System.out.println(result);
}

From source file:net.airvantage.sample.AirVantageExampleFlow2.java

public static void main(String[] args) {

    String apiUrl = "https://na.airvantage.net/api";
    // Replace these with your own api key and secret
    String apiKey = "your_app_id";
    String apiSecret = "your_api_secret";

    String login = null;//from w  w w .jav a2  s .  c o m
    String password = null;
    String access_token = null;

    Scanner in = new Scanner(System.in);

    System.out.println("=== AirVantage's OAuth Workflow ===");
    System.out.println();

    // Obtain User/Password
    System.out.println("Enter your login:");
    System.out.print(">>");
    login = in.nextLine();
    System.out.println();
    System.out.println("...and your password:");
    System.out.print(">>");
    password = in.nextLine();
    System.out.println();

    // Get the Access Token
    System.out.println("Getting the Access Token...");
    System.out.println(apiUrl + "/oauth/token?grant_type=password&username=" + login + "&password=" + password
            + "&client_id=" + apiKey + "&client_secret=" + apiSecret);
    try {
        access_token = Request
                .Get(apiUrl + "/oauth/token?grant_type=password&username=" + login + "&password=" + password
                        + "&client_id=" + apiKey + "&client_secret=" + apiSecret)
                .execute().handleResponse(new ResponseHandler<String>() {

                    public String handleResponse(final HttpResponse response) throws IOException {
                        StatusLine statusLine = response.getStatusLine();
                        HttpEntity entity = response.getEntity();
                        if (statusLine.getStatusCode() >= 300) {
                            throw new HttpResponseException(statusLine.getStatusCode(),
                                    statusLine.getReasonPhrase());
                        }
                        if (entity == null) {
                            throw new ClientProtocolException("Response contains no content");
                        }

                        try {
                            String content = IOUtils.toString(entity.getContent());
                            JSONObject result = new JSONObject(content);
                            return result.getString("access_token");
                        } catch (JSONException e) {
                            throw new ClientProtocolException("Malformed JSON", e);
                        }
                    }

                });

        System.out.println("Got the Access Token!");
        System.out.println("(if you're curious it looks like this: " + access_token + " )");
        System.out.println();

        // Now let's go and ask for a protected resource!
        System.out.println("Now we're going to get info about the current user...");

        JSONObject result = Request.Get(apiUrl + "/v1/users/current?access_token=" + access_token).execute()
                .handleResponse(new ResponseHandler<JSONObject>() {

                    public JSONObject handleResponse(final HttpResponse response) throws IOException {
                        StatusLine statusLine = response.getStatusLine();
                        HttpEntity entity = response.getEntity();
                        if (statusLine.getStatusCode() >= 300) {
                            throw new HttpResponseException(statusLine.getStatusCode(),
                                    statusLine.getReasonPhrase());
                        }
                        if (entity == null) {
                            throw new ClientProtocolException("Response contains no content");
                        }

                        try {
                            String content = IOUtils.toString(entity.getContent());
                            return new JSONObject(content);
                        } catch (JSONException e) {
                            throw new ClientProtocolException("Malformed JSON", e);
                        }
                    }

                });

        System.out.println("Got it! Let's see what we found...");
        System.out.println();
        System.out.println(result.toString());

        System.out.println();
        System.out.println("That's it man! Go and build something awesome with AirVantage! :)");
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.aos.protocol.http.httpcommon.FluentResponseHandling.java

public static void main(String... args) throws Exception {
    Document result = Request.Get("http://somehost/content").execute()
            .handleResponse(new ResponseHandler<Document>() {

                public Document handleResponse(final HttpResponse response) throws IOException {
                    StatusLine statusLine = response.getStatusLine();
                    HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }//from w  w w  . jav  a  2s  .co  m
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                    try {
                        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                        ContentType contentType = ContentType.getOrDefault(entity);
                        if (!contentType.equals(ContentType.APPLICATION_XML)) {
                            throw new ClientProtocolException("Unexpected content type:" + contentType);
                        }
                        Charset charset = contentType.getCharset();
                        if (charset == null) {
                            charset = HTTP.DEF_CONTENT_CHARSET;
                        }
                        return docBuilder.parse(entity.getContent(), charset.name());
                    } catch (ParserConfigurationException ex) {
                        throw new IllegalStateException(ex);
                    } catch (SAXException ex) {
                        throw new ClientProtocolException("Malformed XML document", ex);
                    }
                }

            });
    // Do something useful with the result
    System.out.println(result);
}

From source file:de.mpg.imeji.logic.export.Export.java

public static Export factory(Map<String, String[]> params) throws HttpResponseException {
    Export export = null;//from   www  .ja v  a  2s . com
    boolean supportedFormat = false;
    boolean supportedType = false;

    String format = getParam(params, "format");
    String type = getParam(params, "type");

    if (format == null || format.equals("")) {
        throw new HttpResponseException(400, "Required parameter 'format' is missing.");
    }

    if ("rdf".equals(format)) {
        supportedFormat = true;

        if (type == null || type.equals("")) {
            throw new HttpResponseException(400, "Required parameter 'type' is missing.");
        }

        if (type.equalsIgnoreCase("image")) {
            supportedType = true;
            export = new RDFImageExport();
        } else if (type.equalsIgnoreCase("collection")) {
            supportedType = true;
            export = new RDFCollectionExport();
        } else if (type.equalsIgnoreCase("album")) {
            supportedType = true;
            export = new RDFAlbumExport();
        } else if (type.equals("profile")) {
            supportedType = true;
            export = new RDFProfileExport();
        }
    }

    else if ("jena".equals(format) || format == null) {
        supportedFormat = true;
        supportedType = true; //default, no type necessary here

        export = new JenaExport();
    }

    else if ("sitemap".equals(format)) {
        supportedFormat = true;
        supportedType = true;//default, no type necessary here

        export = new SitemapExport();
    }

    if (!supportedFormat) {
        throw new HttpResponseException(400, "Format " + format + " is not supported.");
    }
    if (!supportedType) {
        throw new HttpResponseException(400, "Type " + type + " is not supported.");
    }

    export.setParams(params);
    export.init();

    return export;
}

From source file:org.hardisonbrewing.s3j.HttpUtil.java

public static void validateResponseCode(HttpResponse httpResponse) throws HttpResponseException {

    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    if (statusCode < 200 || statusCode >= 300) {
        String reasonPhrase = statusLine.getReasonPhrase();
        throw new HttpResponseException(statusCode, reasonPhrase);
    }//from   w w w  .  ja  v  a 2  s.  c  o  m
}

From source file:de.mpg.imeji.logic.export.format.XMLExport.java

/**
 * Factory for {@link XMLExport}/*www.  j  a v  a  2 s.c om*/
 * 
 * @param type
 * @return
 * @throws HttpResponseException
 */
public static XMLExport factory(String type) throws HttpResponseException {
    if ("image".equals(type)) {
        return new XMLItemsExport();
    } else if ("profile".equals(type)) {
        return new XMLMdProfileExport();
    }
    throw new HttpResponseException(400, "Type " + type + " is not supported.");
}

From source file:com.commonsware.android.tuning.downloader.ByteArrayResponseHandler.java

public byte[] handleResponse(final HttpResponse response) throws IOException, HttpResponseException {
    StatusLine statusLine = response.getStatusLine();

    if (statusLine.getStatusCode() >= 300) {
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }//from   ww w  .  j  ava2  s  . co m

    HttpEntity entity = response.getEntity();

    if (entity == null) {
        return (null);
    }

    return (EntityUtils.toByteArray(entity));
}

From source file:com.github.rnewson.couchdb.lucene.util.ErrorPreservingResponseHandler.java

public String handleResponse(final org.ektorp.http.HttpResponse response)
        throws HttpResponseException, IOException {
    String str = IOUtils.toString(response.getContent());
    if (response.getCode() >= 300) {
        throw new HttpResponseException(response.getCode(), str);
    }/*from   www.j a v a2s  . co  m*/

    return str;
}

From source file:de.mpg.imeji.logic.export.format.ExplainExport.java

/**
 * Factory for {@link ExplainExport}//from www. j a v  a2 s .  com
 * 
 * @param type
 * @return
 * @throws HttpResponseException
 */
public static ExplainExport factory(String type) throws HttpResponseException {
    if ("search".equals(type)) {
        return new SearchExplainExport();
    } else if ("metadata".equals(type)) {
        return new MetadataExplainExport();
    }
    throw new HttpResponseException(400, "Type " + type + " is not supported.");
}

From source file:org.eclipse.lyo.testsuite.server.trsutils.HttpErrorHandler.java

/**
 * Handle a possible HTTP error response.
 * //from  w  w w.j a v  a 2  s .  c  om
 * @param response
 *            The HTTP response to handle; must not be <code>null</code>
 * @throws HttpResponseException
 *             if the response status code maps to an exception class
 */
public static void responseToException(HttpResponse response) throws HttpResponseException {
    if (response == null)
        throw new IllegalArgumentException(Messages.getServerString("http.error.handler.null.argument")); //$NON-NLS-1$

    Integer status = Integer.valueOf(response.getStatusLine().getStatusCode());

    //Create detail message from response status line and body
    String reasonPhrase = response.getStatusLine().getReasonPhrase();

    StringBuilder message = new StringBuilder(reasonPhrase == null ? "" : reasonPhrase); //$NON-NLS-1$

    if (response.getEntity() != null) {
        try {
            String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            if (body != null && body.length() != 0) {
                message.append('\n');
                message.append(body);
            }
        } catch (IOException e) {
        } // ignore, since the original error needs to be reported
    }

    throw new HttpResponseException(status, message.toString());
}