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

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.aquatest.dbinterface.tools.DatabaseUpdater.java

/**
 * Run the updater to synchronise the device with the server. </p> Method
 * cycles through all the database tables, and for each one, it retrieves
 * records that have been added, changed or deleted.
 *//*from w w w.  j  a  va2s. c om*/
public void run() {
    try {
        long updateTime = System.currentTimeMillis();
        boolean result;

        Vector<String> tables = getTables();
        sendMessage("Table list downloaded: " + tables.size() + " tables found.", ITEM_COMPLETE);

        // begin database transaction
        dA.database.beginTransaction();

        try {

            // loop through all the tables
            int tableCount = tables.size();
            for (int i = 0; i < tableCount; i++) {
                String tableName = tables.get(i);
                int k = i + 1;

                // ignore authoritymanager table
                if (tableName.compareTo("authoritymanager") == 0) {
                    continue;
                } // if

                // retrieve ADDED rows
                sendMessage(tableName + " (table " + k + "/" + tableCount + "): retrieving new records...",
                        ITEM_COMPLETE);
                result = fetchAndExecuteQueries(TYPE_ADDED, tableName);

                if (!result) {
                    // Log.v("THREAD", "KILLING");
                    sendMessage("Update cancelled!", CANCELLED);
                    return;
                } // if

                // retrieve UPDATED rows
                sendMessage(tableName + " (table " + k + "/" + tableCount + "): retrieving updated records...",
                        ITEM_COMPLETE);
                result = fetchAndExecuteQueries(TYPE_UPDATED, tableName);

                if (!result) {
                    // Log.v("THREAD", "KILLING");
                    sendMessage("Update cancelled!", CANCELLED);
                    return;
                } // if

                // retrieve DELETED rows
                sendMessage(tableName + " (table " + k + "/" + tableCount + "): retrieving deleted rows...",
                        ITEM_COMPLETE);
                result = fetchAndExecuteQueries(TYPE_DELETED, tableName);

                if (!result) {
                    // Log.v("THREAD", "KILLING");
                    sendMessage("Update cancelled!", CANCELLED);
                    return;
                } // if
            } // for

            // signal transaction can be committed
            dA.database.setTransactionSuccessful();
        } finally {
            // commit or rollback transaction
            dA.database.endTransaction();

        }

        // return success in a Bundle
        Bundle b = new Bundle();
        b.putString("msg", "Update complete!");
        b.putLong("time", updateTime);
        sendMessage(b, COMPLETE);

    } catch (JSONException jE) {
        sendMessage(jE.getMessage(), ERROR);
        return;
    } catch (ClientProtocolException cE) {
        sendMessage(cE.getMessage() + " This is possibly caused by a lack of connectivity. "
                + "Restart the app and try again after ensuring you have a valid connection.", ERROR);
        return;
    } catch (IOException iE) {
        sendMessage(iE.getMessage() + " This is possibly caused by a lack of connectivity. "
                + "Restart the app and try again after ensuring you have a valid connection.", ERROR);
        return;
    } catch (SQLiteException sE) {
        sendMessage("A SQLite exception occured: " + sE.getMessage(), ERROR);
        return;
    } // catch
}

From source file:net.evecom.androidecssp.base.BaseActivity.java

/**
 * /*from  ww w .  j av  a  2s.  c  om*/
 *  dictValue dictKey TextViewDictName
 * 
 * @author Mars zhang
 * @created 2015-11-25 9:50:55
 * @param dictKey
 * @param value
 * @param view
 */
protected void setDictNameByValueToView(final String dictKey, final String dictValue, final TextView view) {
    final Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case MESSAGETYPE_01:
                view.setText(msg.getData().getString("dictname"));
                break;
            default:
                break;
            }
        };
    };
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                HashMap<String, String> entityMap = new HashMap<String, String>();
                entityMap.put("dictkey", dictKey);
                String result = connServerForResultPost("jfs/ecssp/mobile/pubCtr/getDictByKey", entityMap);
                List<BaseModel> baseModels = getObjsInfo(result);
                HashMap<String, String> keyValehashmap = new HashMap<String, String>();
                for (int i = 0; i < baseModels.size(); i++) {
                    keyValehashmap.put(baseModels.get(i).get("dictvalue") + "",
                            baseModels.get(i).get("name") + "");
                }
                String dictname = ifnull(keyValehashmap.get(dictValue), "");
                Message message = new Message();
                Bundle mbundle = new Bundle();
                mbundle.putString("dictname", dictname);
                message.setData(mbundle);
                message.what = MESSAGETYPE_01;
                mHandler.sendMessage(message);
            } catch (ClientProtocolException e) {
                Log.v("mars", e.getMessage());
            } catch (IOException e) {
                Log.v("mars", e.getMessage());
            } catch (JSONException e) {
                Log.v("mars", e.getMessage());
            }
        }
    }).start();

}

From source file:net.evecom.androidecssp.base.BaseActivity.java

/**
 * //w  w w . j av  a 2s  . c  o  m
 *  dictValue dictKey TextViewDictName 
 * 
 * @author Mars zhang
 * @created 2015-11-25 9:50:55
 * @param dictKey
 * @param value
 * @param view
 */
protected void setLikeDictNameByValueToView(final String url, final String dictKey, final String dictValue,
        final TextView view) {
    final Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case MESSAGETYPE_01:
                view.setText(msg.getData().getString("dictname"));
                break;
            default:
                break;
            }
        };
    };
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                HashMap<String, String> entityMap = new HashMap<String, String>();
                entityMap.put("dictkey", dictKey);
                String result = connServerForResultPost(url, entityMap);
                List<BaseModel> baseModels = getObjsInfo(result);
                HashMap<String, String> keyValehashmap = new HashMap<String, String>();
                for (int i = 0; i < baseModels.size(); i++) {
                    keyValehashmap.put(baseModels.get(i).get("dictvalue") + "",
                            baseModels.get(i).get("name") + "");
                }
                String dictname = ifnull(keyValehashmap.get(dictValue), "");
                Message message = new Message();
                Bundle mbundle = new Bundle();
                mbundle.putString("dictname", dictname);
                message.setData(mbundle);
                message.what = MESSAGETYPE_01;
                mHandler.sendMessage(message);
            } catch (ClientProtocolException e) {
                Log.v("mars", e.getMessage());
            } catch (IOException e) {
                Log.v("mars", e.getMessage());
            } catch (JSONException e) {
                Log.v("mars", e.getMessage());
            }
        }
    }).start();

}

From source file:com.smartsheet.api.internal.http.DefaultHttpClient.java

/**
 * Make an HTTP request and return the response.
 *
 * @param smartsheetRequest the smartsheet request
 * @return the HTTP response//from www.  ja  va  2 s  .  c o m
 * @throws HttpClientException the HTTP client exception
 */
public HttpResponse request(HttpRequest smartsheetRequest) throws HttpClientException {
    Util.throwIfNull(smartsheetRequest);
    if (smartsheetRequest.getUri() == null) {
        throw new IllegalArgumentException("A Request URI is required.");
    }

    int attempt = 0;
    long start = System.currentTimeMillis();

    HttpRequestBase apacheHttpRequest;
    HttpResponse smartsheetResponse;

    InputStream bodyStream = null;
    if (smartsheetRequest.getEntity() != null && smartsheetRequest.getEntity().getContent() != null) {
        bodyStream = smartsheetRequest.getEntity().getContent();
    }
    // the retry logic will consume the body stream so we make sure it supports mark/reset and mark it
    boolean canRetryRequest = bodyStream == null || bodyStream.markSupported();
    if (!canRetryRequest) {
        try {
            // attempt to wrap the body stream in a input-stream that does support mark/reset
            bodyStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(bodyStream));
            // close the old stream (just to be tidy) and then replace it with a reset-able stream
            smartsheetRequest.getEntity().getContent().close();
            smartsheetRequest.getEntity().setContent(bodyStream);
            canRetryRequest = true;
        } catch (IOException ignore) {
        }
    }

    // the retry loop
    while (true) {

        apacheHttpRequest = createApacheRequest(smartsheetRequest);

        // Set HTTP headers
        if (smartsheetRequest.getHeaders() != null) {
            for (Map.Entry<String, String> header : smartsheetRequest.getHeaders().entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }
        }

        HttpEntitySnapshot requestEntityCopy = null;
        HttpEntitySnapshot responseEntityCopy = null;
        // Set HTTP entity
        final HttpEntity entity = smartsheetRequest.getEntity();
        if (apacheHttpRequest instanceof HttpEntityEnclosingRequestBase && entity != null
                && entity.getContent() != null) {
            try {
                // we need access to the original request stream so we can log it (in the event of errors and/or tracing)
                requestEntityCopy = new HttpEntitySnapshot(entity);
            } catch (IOException iox) {
                logger.error("failed to make copy of original request entity - {}", iox);
            }

            InputStreamEntity streamEntity = new InputStreamEntity(entity.getContent(),
                    entity.getContentLength());
            streamEntity.setChunked(false); // why?  not supported by library?
            ((HttpEntityEnclosingRequestBase) apacheHttpRequest).setEntity(streamEntity);
        }

        // mark the body so we can reset on retry
        if (canRetryRequest && bodyStream != null) {
            bodyStream.mark((int) smartsheetRequest.getEntity().getContentLength());
        }

        // Make the HTTP request
        smartsheetResponse = new HttpResponse();
        HttpContext context = new BasicHttpContext();
        try {
            long startTime = System.currentTimeMillis();
            apacheHttpResponse = this.httpClient.execute(apacheHttpRequest, context);
            long endTime = System.currentTimeMillis();

            // Set request headers to values ACTUALLY SENT (not just created by us), this would include:
            // 'Connection', 'Accept-Encoding', etc. However, if a proxy is used, this may be the proxy's CONNECT
            // request, hence the test for HTTP method first
            Object httpRequest = context.getAttribute("http.request");
            if (httpRequest != null && HttpRequestWrapper.class.isAssignableFrom(httpRequest.getClass())) {
                HttpRequestWrapper actualRequest = (HttpRequestWrapper) httpRequest;
                switch (HttpMethod.valueOf(actualRequest.getMethod())) {
                case GET:
                case POST:
                case PUT:
                case DELETE:
                    apacheHttpRequest.setHeaders(((HttpRequestWrapper) httpRequest).getAllHeaders());
                    break;
                }
            }

            // Set returned headers
            smartsheetResponse.setHeaders(new HashMap<String, String>());
            for (Header header : apacheHttpResponse.getAllHeaders()) {
                smartsheetResponse.getHeaders().put(header.getName(), header.getValue());
            }
            smartsheetResponse.setStatus(apacheHttpResponse.getStatusLine().getStatusCode(),
                    apacheHttpResponse.getStatusLine().toString());

            // Set returned entities
            if (apacheHttpResponse.getEntity() != null) {
                HttpEntity httpEntity = new HttpEntity();
                httpEntity.setContentType(apacheHttpResponse.getEntity().getContentType().getValue());
                httpEntity.setContentLength(apacheHttpResponse.getEntity().getContentLength());
                httpEntity.setContent(apacheHttpResponse.getEntity().getContent());
                smartsheetResponse.setEntity(httpEntity);
                responseEntityCopy = new HttpEntitySnapshot(httpEntity);
            }

            long responseTime = endTime - startTime;
            logRequest(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy,
                    responseTime);

            if (traces.size() > 0) { // trace-logging of request and response (if so configured)
                RequestAndResponseData requestAndResponseData = RequestAndResponseData.of(apacheHttpRequest,
                        requestEntityCopy, smartsheetResponse, responseEntityCopy, traces);
                TRACE_WRITER.println(requestAndResponseData.toString(tracePrettyPrint));
            }

            if (smartsheetResponse.getStatusCode() == 200) {
                // call successful, exit the retry loop
                break;
            }

            // the retry logic might consume the content stream so we make sure it supports mark/reset and mark it
            InputStream contentStream = smartsheetResponse.getEntity().getContent();
            if (!contentStream.markSupported()) {
                // wrap the response stream in a input-stream that does support mark/reset
                contentStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(contentStream));
                // close the old stream (just to be tidy) and then replace it with a reset-able stream
                smartsheetResponse.getEntity().getContent().close();
                smartsheetResponse.getEntity().setContent(contentStream);
            }
            try {
                contentStream.mark((int) smartsheetResponse.getEntity().getContentLength());
                long timeSpent = System.currentTimeMillis() - start;
                if (!shouldRetry(++attempt, timeSpent, smartsheetResponse)) {
                    // should not retry, or retry time exceeded, exit the retry loop
                    break;
                }
            } finally {
                if (bodyStream != null) {
                    bodyStream.reset();
                }
                contentStream.reset();
            }
            // moving this to finally causes issues because socket is closed (which means response stream is closed)
            this.releaseConnection();

        } catch (ClientProtocolException e) {
            try {
                logger.warn("ClientProtocolException " + e.getMessage());
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                // if this is a PUT and was retried by the http client, the body content stream is at the
                // end and is a NonRepeatableRequest. If we marked the body content stream prior to execute,
                // reset and retry
                if (canRetryRequest && e.getCause() instanceof NonRepeatableRequestException) {
                    if (smartsheetRequest.getEntity() != null) {
                        smartsheetRequest.getEntity().getContent().reset();
                    }
                    continue;
                }
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        } catch (NoHttpResponseException e) {
            try {
                logger.warn("NoHttpResponseException " + e.getMessage());
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                // check to see if the response was empty and this was a POST. All other HTTP methods
                // will be automatically retried by the http client.
                // (POST is non-idempotent and is not retried automatically, but is safe for us to retry)
                if (canRetryRequest && smartsheetRequest.getMethod() == HttpMethod.POST) {
                    if (smartsheetRequest.getEntity() != null) {
                        smartsheetRequest.getEntity().getContent().reset();
                    }
                    continue;
                }
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        } catch (IOException e) {
            try {
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        }
    }
    return smartsheetResponse;
}

From source file:net.vexelon.mobileops.GLBClient.java

private List<NameValuePair> findLoginParams() throws HttpClientException {

    List<NameValuePair> result = new ArrayList<NameValuePair>();
    BufferedReader reader = null;
    long bytesCount = 0;

    try {//from  w w  w  . j  a v  a2 s  .  co  m
        // Get invoice check page
        StringBuilder fullUrl = new StringBuilder(100);
        fullUrl.append(GLBRequestType.LOGIN.getPath()).append("?").append(GLBRequestType.LOGIN.getParams());

        HttpGet httpGet = new HttpGet(fullUrl.toString());
        HttpResponse resp = httpClient.execute(httpGet, httpContext);
        StatusLine status = resp.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_OK) {

            Document doc = Jsoup.parse(resp.getEntity().getContent(), RESPONSE_ENCODING, "");
            Elements inputs = doc.select("input");
            for (Element el : inputs) {
                //               if (Defs.LOG_ENABLED) {
                //                  Log.v(Defs.LOG_TAG, "ELEMENT: " + el.tagName());
                //               }
                Attributes attrs = el.attributes();
                //               for (Attribute attr : attrs) {
                //                  if (Defs.LOG_ENABLED) {
                //                     Log.v(Defs.LOG_TAG, " " + attr.getKey() + "=" + attr.getValue());
                //                  }
                //               }

                String elName = attrs.get("name");
                if (elName.equalsIgnoreCase("lt") || elName.equalsIgnoreCase("execution")) {
                    result.add(new BasicNameValuePair(elName, attrs.get("value")));
                }
            }
        } else {
            throw new HttpClientException(status.getReasonPhrase(), status.getStatusCode());
        }

        // close current stream reader
        //         if (reader != null) try { reader.close(); } catch (IOException e) {};

    } catch (ClientProtocolException e) {
        throw new HttpClientException("Client protocol error!" + e.getMessage(), e);
    } catch (IOException e) {
        throw new HttpClientException("Client error!" + e.getMessage(), e);
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e) {
            }
        ;

        addDownloadedBytesCount(bytesCount);
    }

    return result;
}

From source file:com.stepsdk.android.api.APIClient.java

public HttpEntity httpGet(String url, Map<String, String> headerParams)
        throws NetworkDownException, HttpGetException {
    HttpEntity entity = null;/*from w  w w . j av a 2s  .c  om*/

    mHttpclient = new DefaultHttpClient();

    ClientConnectionManager mgr = mHttpclient.getConnectionManager();
    HttpParams params = mHttpclient.getParams();
    if (WEB_USER_AGENT != null)
        params.setParameter(CoreProtocolPNames.USER_AGENT, WEB_USER_AGENT);
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(params, timeoutSocket);
    mHttpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
            params);

    // Allow redirection from server
    // ref: http://stackoverflow.com/questions/3658721/httpclient-4-error-302-how-to-redirect
    mHttpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            boolean isRedirect = super.isRedirectRequested(response, context);
            if (!isRedirect) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 302) {
                    return true;
                }
            }
            return isRedirect;
        }
    });

    HttpGet get = new HttpGet(url);

    if (headerParams == null) {
        headerParams = new HashMap<String, String>();
    }

    Iterator<String> i = headerParams.keySet().iterator();

    while (i.hasNext()) {
        String key = i.next();
        get.addHeader(key, headerParams.get(key));
    }

    Integer retryRemaining = 3;

    while (entity == null) {
        try {

            if (!DeviceUtil.checkPermission(mContext, "android.permission.ACCESS_NETWORK_STATE"))
                throw new NetworkDownException(
                        "ACCESS_NETWORK_STATE permission not set in AndroidManifest.xml");

            if (!DeviceUtil.checkPermission(mContext, "android.permission.INTERNET"))
                throw new NetworkDownException("INTERNET permission not set in AndroidManifest.xml");

            if (!NetworkUtil.isOnline(mContext))
                throw new NetworkDownException();

            HttpResponse response = mHttpclient.execute(get);
            if (response.getStatusLine().getStatusCode() == 404)
                throw new HttpGetException("404");
            entity = response.getEntity();
        } catch (ClientProtocolException e) {
            if (retryRemaining-- != 0) {
                entity = null;
            } else {
                throw new HttpGetException(e.getMessage());
            }
        } catch (IOException e) {
            if (retryRemaining-- != 0) {
                entity = null;
            } else {
                throw new HttpGetException(e.getMessage());
            }
        }
    }

    return entity;
}

From source file:li.zeitgeist.api.ZeitgeistApi.java

/**
 * Execute a HTTP request and parse the result as JSON, also unifies
 * Exceptions into the ZeitgeistError class.
 * @param request//from   w w w  . j  a  v a2 s  .com
 * @return json map of primitives.
 * @throws ZeitgeistError
 */
private Map<String, ?> executeRequest(HttpRequestBase request) throws ZeitgeistError {
    Map<String, ?> jsonObject = null;

    try {
        HttpResponse response = this.client.execute(request);
        String jsonString = EntityUtils.toString(response.getEntity());
        jsonObject = parseJson(jsonString);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) { // parse json into an ZeitgeistException and throw
            ZeitgeistError error = null;
            if (((String) jsonObject.get("type")).equals("CreateItemError")) {
                error = new CreateItemError(jsonObject, baseUrl);
            } else {
                error = new ZeitgeistError(jsonObject);
            }

            throw error;
        }
    } catch (ClientProtocolException e) {
        throw new ZeitgeistError("ClientProtocolException: " + e.getMessage());
    } catch (IOException e) {
        throw new ZeitgeistError("IOException: " + e.getMessage());
    } catch (ZeitgeistError e) {
        throw e; // just passthrough
    }

    return jsonObject;
}

From source file:mixedserver.protocol.jsonrpc.client.HTTPSession.java

private String sendEntity(HttpEntity entity) throws RPCException {
    HttpPost request = new HttpPost(this.uri);
    request.setEntity(entity);//from   w w  w  . j a  v a 2 s .c om

    HttpResponse response;
    String responseString = null;
    try {
        Date before = new Date();
        response = http().execute(request, localContext);
        Date after = new Date();

        logger.debug("" + (after.getTime() - before.getTime()));

        responseString = EntityUtils.toString(response.getEntity());
        responseString = responseString.trim();

    } catch (ClientProtocolException e) {
        throw new RPCException("???");
    } catch (IOException e) {
        throw new RPCException("", RPCException.ERROR_CODE_NETWORK_ERROR);
    } catch (Exception e) {
        if (e.getClass().getName().equals("NetworkOnMainThreadException")) {
            throw new RPCException("????");
        }

        throw new RPCException("http:" + e.getMessage());
    }

    return responseString;
}

From source file:org.commonjava.propulsor.client.http.ClientHttpSupport.java

public void putWithStream(final String path, final InputStream stream, final int... responseCodes)
        throws ClientHttpException {
    connect();/*ww  w .java  2 s  . co m*/

    final HttpPut put = newRawPut(buildUrl(baseUrl, path));
    final CloseableHttpClient client = newClient();
    CloseableHttpResponse response = null;
    try {
        put.setEntity(new InputStreamEntity(stream));

        response = client.execute(put);
        final StatusLine sl = response.getStatusLine();
        if (!validResponseCode(sl.getStatusCode(), responseCodes)) {
            throw new ClientProtocolException(new ClientHttpException(sl.getStatusCode(),
                    "Error in response from: %s.\n%s", path, new ClientHttpResponseErrorDetails(response)));
        }

    } catch (final ClientProtocolException e) {
        final Throwable cause = e.getCause();
        if (cause != null && (cause instanceof ClientHttpException)) {
            throw (ClientHttpException) cause;
        }

        throw new ClientHttpException("Client request failed: %s", e, e.getMessage());
    } catch (final IOException e) {
        throw new ClientHttpException("Client request failed: %s", e, e.getMessage());
    } finally {
        cleanupResources(put, response, client);
    }
}