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

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.ymkm.lib.http.HttpRequester.java

private static HttpResponseHolder request(HttpRequestHolder loadReq) {
    HttpClient client = null;// w w  w.  ja va2 s . c  o m

    ExecutableRequest req = loadReq.http;
    HttpRequestListener listener = loadReq.listener;
    HttpParams params = req.getParams();

    if (null == params) {
        params = new BasicHttpParams();
    }
    if (null != listener) {
        listener.setRequestParams(params);
    }

    // Use Android specific client if available
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
        client = android.net.http.AndroidHttpClient.newInstance(android_user_agent);
    } else {
        // Sets up the http part of the service.
        final SchemeRegistry supportedSchemes = new SchemeRegistry();
        // Register the "http" protocol scheme, it is required
        // by the default operator to look up socket factories.
        final SocketFactory sf = PlainSocketFactory.getSocketFactory();
        supportedSchemes.register(new Scheme("http", sf, 80));
        supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);
        client = new DefaultHttpClient(ccm, params);
    }
    req.setParams(params);

    if (null != listener) {
        listener.setHttpClient(client);
    }

    HttpResponse resp = null;
    HttpResponseHolder holder = new HttpResponseHolder();
    holder.uri = Uri.parse(req.getURI().toString());

    try {
        resp = client.execute(req);
        holder.returnCode = resp.getStatusLine().getStatusCode();
        Header[] hdrs = resp.getAllHeaders();
        if (hdrs.length > 0) {
            for (Header h : hdrs) {
                holder.headers.put(h.getName(), h.getValue());
            }
        }

        if ("application/octet-stream".equals(resp.getFirstHeader("Content-Type").getValue())) {
            int len = 0;
            byte[] buffer = new byte[1024];
            InputStream is = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            try {
                is = resp.getEntity().getContent();

                while (0 < (len = is.read(buffer))) {
                    baos.write(buffer, 0, len);
                }
                holder.responseBytes = baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (null != baos) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        } else {
            Reader r = null;
            int length = 1024;
            if (null != resp.getFirstHeader("Content-Length")) {
                length = Integer.parseInt(resp.getFirstHeader("Content-Length").getValue());
            }
            // Set initial size for StringBuilder buffer to be content length + some extra
            StringBuilder sb = new StringBuilder(length + 10);
            try {
                r = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
                String s = null;
                while ((s = ((BufferedReader) r).readLine()) != null) {
                    sb.append(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (null != r) {
                    try {
                        r.close();
                    } catch (IOException e) {
                    }
                }
            }
            holder.responseBody = sb.toString();
        }
        return holder;
    } catch (HttpResponseException hre) {
        holder.responseBody = hre.getMessage();
        holder.returnCode = hre.getStatusCode();
        return holder;
    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
        holder.responseBody = cpe.getMessage();
        holder.returnCode = 500;
        return holder;
    } catch (Exception exc) {
        exc.printStackTrace();
        holder.responseBody = exc.getMessage();
        holder.returnCode = 500;
        return holder;
    } finally {
        // Use Android specific client if available
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
            ((android.net.http.AndroidHttpClient) client).close();
        }
    }
}

From source file:com.github.rnewson.couchdb.lucene.DatabaseIndexer.java

public Void handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
    final HttpEntity entity = response.getEntity();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
    String line;//from  w  ww  .  j  av a2 s .  c  o m
    loop: while ((line = reader.readLine()) != null) {
        maybeCommit();

        // Heartbeat.
        if (line.length() == 0) {
            logger.trace("heartbeat");
            continue loop;
        }

        try {
            final JSONObject json = new JSONObject(line);

            if (json.has("error")) {
                logger.warn("Indexing stopping due to error: " + json);
                break loop;
            }

            if (json.has("last_seq")) {
                logger.info("End of changes detected.");
                break loop;
            }

            final UpdateSequence seq = UpdateSequence.parseUpdateSequence(json.getString("seq"));
            final String id = json.getString("id");
            CouchDocument doc;
            if (!json.isNull("doc")) {
                doc = new CouchDocument(json.getJSONObject("doc"));
            } else {
                // include_docs=true doesn't work prior to 0.11.
                try {
                    doc = database.getDocument(id);
                } catch (final HttpResponseException e) {
                    switch (e.getStatusCode()) {
                    case HttpStatus.SC_NOT_FOUND:
                        doc = CouchDocument.deletedDocument(id);
                        break;
                    default:
                        logger.warn("Failed to fetch " + id);
                        break loop;
                    }
                }
            }

            if (id.startsWith("_design")) {
                if (seq.isLaterThan(ddoc_seq)) {
                    logger.info("Exiting due to design document change.");
                    break loop;
                }
            }

            if (doc.isDeleted()) {
                for (final IndexState state : states.values()) {
                    state.writer.deleteDocuments(new Term("_id", id));
                    state.setPendingSequence(seq);
                    state.readerDirty = true;
                }
            } else {
                for (final Entry<View, IndexState> entry : states.entrySet()) {
                    final View view = entry.getKey();
                    final IndexState state = entry.getValue();

                    if (seq.isLaterThan(state.pending_seq)) {
                        final Collection<Document> docs;
                        try {
                            docs = state.converter.convert(doc, view.getDefaultSettings(), database);
                        } catch (final Exception e) {
                            logger.warn(id + " caused " + e.getMessage());
                            continue loop;
                        }

                        state.writer.updateDocuments(new Term("_id", id), docs, view.getAnalyzer());
                        state.setPendingSequence(seq);
                        state.readerDirty = true;
                    }
                }
            }
        } catch (final JSONException e) {
            logger.error("JSON exception in changes loop", e);
            break loop;
        }
    }
    req.abort();
    return null;
}

From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java

/**
 * Utility method to execute any type of http request (except delete), to
 * catch any exceptions thrown and return the response string.
 * //from www .j av a2  s .  c o m
 * @param hr
 * @return
 * @throws SkytapException
 * @throws IOException
 * @throws ParseException
 */
public static String executeHttpRequest(HttpRequestBase hr) throws SkytapException {

    boolean retryHttpRequest = true;
    int retryCount = 1;
    String responseString = "";
    while (retryHttpRequest == true) {
        HttpClient httpclient = new DefaultHttpClient();
        //
        // Set timeouts for httpclient requests to 60 seconds
        //
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 60000);
        HttpConnectionParams.setSoTimeout(httpclient.getParams(), 60000);
        //
        responseString = "";
        HttpResponse response = null;
        try {
            Date myDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
            String myDateString = sdf.format(myDate);

            JenkinsLogger.log(myDateString + "\n" + "Executing Request: " + hr.getRequestLine());
            response = httpclient.execute(hr);

            String responseStatusLine = response.getStatusLine().toString();
            if (responseStatusLine.contains("423 Locked")) {
                retryCount = retryCount + 1;
                if (retryCount > 5) {
                    retryHttpRequest = false;
                    JenkinsLogger.error("Object busy too long - giving up.");
                } else {
                    JenkinsLogger.log("Object busy - Retrying...");
                    try {
                        Thread.sleep(15000);
                    } catch (InterruptedException e1) {
                        JenkinsLogger.error(e1.getMessage());
                    }
                }
            } else if (responseStatusLine.contains("409 Conflict")) {

                throw new SkytapException(responseStatusLine);

            } else {

                JenkinsLogger.log(response.getStatusLine().toString());
                HttpEntity entity = response.getEntity();
                responseString = EntityUtils.toString(entity, "UTF-8");
                retryHttpRequest = false;
            }

        } catch (HttpResponseException e) {
            retryHttpRequest = false;
            JenkinsLogger.error("HTTP Response Code: " + e.getStatusCode());

        } catch (ParseException e) {
            retryHttpRequest = false;
            JenkinsLogger.error(e.getMessage());

        } catch (InterruptedIOException e) {
            Date myDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
            String myDateString = sdf.format(myDate);

            retryCount = retryCount + 1;
            if (retryCount > 5) {
                retryHttpRequest = false;
                JenkinsLogger.error("API Timeout - giving up. " + e.getMessage());
            } else {
                JenkinsLogger.log(myDateString + "\n" + e.getMessage() + "\n" + "API Timeout - Retrying...");
            }
        } catch (IOException e) {
            retryHttpRequest = false;
            JenkinsLogger.error(e.getMessage());
        } finally {
            if (response != null) {
                // response will be null if this is a timeout retry
                HttpEntity entity = response.getEntity();
                try {
                    responseString = EntityUtils.toString(entity, "UTF-8");
                } catch (IOException e) {
                    // JenkinsLogger.error(e.getMessage());
                }
            }

            httpclient.getConnectionManager().shutdown();
        }
    }

    return responseString;

}

From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java

/**
 * Utility method used to execute an http delete. Returns the status line
 * which can be parsed as desired by the caller.
 * /*ww w  .  j  a v  a  2  s.c om*/
 * @param hd
 * @return
 * @throws SkytapException
 */
public static String executeHttpDeleteRequest(HttpDelete hd) {

    String responseString = "";

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;

    JenkinsLogger.log("Executing Request: " + hd.getRequestLine());

    try {

        response = httpclient.execute(hd);
        String statusLine = response.getStatusLine().toString();
        JenkinsLogger.log(statusLine);
        HttpEntity entity = response.getEntity();
        responseString = EntityUtils.toString(entity, "UTF-8");

    } catch (HttpResponseException e) {

        JenkinsLogger.error("HTTP Response Code: " + e.getStatusCode());

    } catch (ParseException e) {
        JenkinsLogger.error(e.getMessage());
    } catch (IOException e) {
        JenkinsLogger.error(e.getMessage());
    } finally {

        HttpEntity entity = response.getEntity();
        try {
            responseString = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            // JenkinsLogger.error(e.getMessage());
        }

        httpclient.getConnectionManager().shutdown();
    }

    return responseString;
}