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

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.exoplatform.social.client.api.util.SocialHttpClientSupport.java

/**
 * Invokes the social rest service via Get method
 * @param targetURL // w  w  w .  j  a v  a2 s.  c  o  m
 * @param authPolicy POLICY.NO_AUTH/POLICY.BASIC_AUTH
 * @param params HttpParams for Request
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static HttpResponse executeGet(String targetURL, POLICY authPolicy, HttpParams params)
        throws SocialHttpClientException {
    SocialHttpClient httpClient = SocialHttpClientImpl.newInstance();
    if (POLICY.BASIC_AUTH == authPolicy) {
        try {
            httpClient.setBasicAuthenticateToRequest();
        } catch (SocialClientLibException e) {
            throw new SocialHttpClientException(e.getMessage(), e);
        }
    }

    HttpGet httpGet = new HttpGet(targetURL);
    Header header = new BasicHeader("Content-Type", "application/json");
    httpGet.setHeader(header);
    HttpHost targetHost = new HttpHost(SocialClientContext.getHost(), SocialClientContext.getPort(),
            SocialClientContext.getProtocol());
    //Get method with the HttpParams
    if (params != null) {
        httpGet.setParams(params);
    }

    try {
        HttpResponse response = httpClient.execute(targetHost, httpGet);
        //handleError(response);
        //Debugging in the devlopment mode
        if (SocialClientContext.isDeveloping()) {
            dumpHttpResponsetHeader(response);
            dumpContent(response);
        }
        return response;
    } catch (ClientProtocolException cpex) {
        throw new SocialHttpClientException(cpex.toString(), cpex);
    } catch (IOException ioex) {
        throw new SocialHttpClientException(ioex.toString(), ioex);
    }
}

From source file:org.exoplatform.social.client.api.util.SocialHttpClientSupport.java

/**
 * Invokes the social rest service via Delete method with HttpParams
 * @param targetURL // www .ja  va2s .  c o  m
 * @param authPolicy POLICY.NO_AUTH/POLICY.BASIC_AUTH
 * @param params HttpParams for Request
 * @return
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public static HttpResponse executeDelete(String targetURL, POLICY authPolicy, HttpParams params)
        throws SocialHttpClientException {
    HttpHost targetHost = new HttpHost(SocialClientContext.getHost(), SocialClientContext.getPort(),
            SocialClientContext.getProtocol());
    SocialHttpClient httpClient = SocialHttpClientImpl.newInstance();

    if (POLICY.BASIC_AUTH == authPolicy) {
        try {
            httpClient.setBasicAuthenticateToRequest();
        } catch (SocialClientLibException e) {
            new SocialHttpClientException(e.getMessage(), e);
        }
    }

    HttpDelete httpDelete = new HttpDelete(targetURL);
    Header header = new BasicHeader("Content-Type", "application/json");
    httpDelete.setHeader(header);
    //Delete method with the HttpParams
    if (params != null) {
        httpDelete.setParams(params);
    }
    try {
        HttpResponse response = httpClient.execute(targetHost, httpDelete);
        //handleError(response);
        //Debugging in the devlopment mode
        if (SocialClientContext.isDeveloping()) {
            dumpHttpResponsetHeader(response);
            dumpContent(response);
        }
        return response;
    } catch (ClientProtocolException cpex) {
        throw new SocialHttpClientException(cpex.toString(), cpex);
    } catch (IOException ioex) {
        throw new SocialHttpClientException(ioex.toString(), ioex);
    }

}

From source file:org.exoplatform.social.client.api.util.SocialHttpClientSupport.java

/**
 * Invokes the social rest service via Post method
 * @param targetURL /*from w  w  w.  j a  v  a2 s  .  c  o m*/
 * @param authPolicy POLICY.NO_AUTH/POLICY.BASIC_AUTH
 * @param params HttpParams for Request
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static HttpResponse executePost(String targetURL, POLICY authPolicy, HttpParams params, Model model)
        throws SocialHttpClientException {
    HttpHost targetHost = new HttpHost(SocialClientContext.getHost(), SocialClientContext.getPort(),
            SocialClientContext.getProtocol());
    SocialHttpClient httpClient = SocialHttpClientImpl.newInstance();

    if (POLICY.BASIC_AUTH == authPolicy) {
        try {
            httpClient.setBasicAuthenticateToRequest();
        } catch (SocialClientLibException e) {
            throw new SocialHttpClientException(e.getMessage(), e);
        }
    }

    HttpPost httpPost = new HttpPost(targetURL);
    Header header = new BasicHeader("Content-Type", "application/json");
    httpPost.setHeader(header);
    //Post method with the HttpParams
    if (params != null) {
        httpPost.setParams(params);
    }
    try {

        //Provides when uses post so does not have any data.
        byte[] postData = convertModelToByteArray(model);
        if (postData != null) {
            ByteArrayEntity entity = new ByteArrayEntity(convertModelToByteArray(model));
            httpPost.setEntity(entity);
        }
        HttpResponse response = httpClient.execute(targetHost, httpPost);

        //handleError(response);
        //Debugging in the devlopment mode
        if (SocialClientContext.isDeveloping()) {
            dumpHttpResponsetHeader(response);
            dumpContent(response);
        }
        return response;
    } catch (ClientProtocolException cpex) {
        throw new SocialHttpClientException(cpex.toString(), cpex);
    } catch (IOException ioex) {
        throw new SocialHttpClientException(ioex.toString(), ioex);
    }

}

From source file:info.unyttig.helladroid.newzbin.NewzBinController.java

/**
 * Fetches a report from Newzbin based on a given id.
 * However if the report is already cached, its just fetched from the hashmap.
 * @param id/*from   w  w  w  .  java  2  s  .  com*/
 */
public static NewzBinReport getReportInfo(int id) {
    if (detailedReports.containsKey(id))
        return detailedReports.get(id);

    String url = NBAPIURL + "reportinfo/";
    HashMap<String, String> searchOptions = new HashMap<String, String>();
    searchOptions.put("id", "" + id);
    try {
        HttpResponse response = doPost(url, searchOptions);
        checkReturnCode(response.getStatusLine().getStatusCode(), false);
        InputStream is = response.getEntity().getContent();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewzBinDRHandler handler = new NewzBinDRHandler();
        if (reports.containsKey(id))
            handler.nbdr = reports.get(id);
        xr.setContentHandler(handler);
        xr.parse(new InputSource(is));
        detailedReports.put(id, handler.getParsedData());
        // Temp
        ArrayList<NewzBinReportComment> comments = handler.nbdr.getComments();
        Log.i(LOG_NAME, "Comments size: " + comments.size());
        Iterator<NewzBinReportComment> sd = comments.iterator();
        while (sd.hasNext()) {
            NewzBinReportComment nrc = sd.next();
            Log.i(LOG_NAME, nrc.toString());
        }
        return handler.getParsedData();
    } catch (ClientProtocolException e) {
        Log.e(LOG_NAME, "ClientProtocol thrown: ", e);
    } catch (IOException e) {
        Log.e(LOG_NAME, "IOException thrown: ", e);
    } catch (NewzBinPostReturnCodeException e) {
        Log.e(LOG_NAME, "POST ReturnCode error: " + e.toString());
    } catch (ParserConfigurationException e) {
        Log.e(LOG_NAME, "ParserError thrown: ", e);
    } catch (SAXException e) {
        Log.e(LOG_NAME, "SAXError thrown: ", e);
    }
    return null;
}

From source file:com.alibaba.akita.io.HttpInvoker.java

public static String get(String url, Header[] headers) throws AkServerStatusException, AkInvokeException {
    Log.v(TAG, "get:" + url);
    //url = url.replace("gw.api.alibaba.com", "205.204.112.73"); // usa ocean
    //url = url.replace("gw.api.alibaba.com", "172.20.128.127");  // yufa
    //url = url.replace("mobi.aliexpress.com", "172.20.226.142");
    String retString = null;/*from   w  w  w.  j a  va 2  s  .co m*/
    try {
        HttpGet request = new HttpGet(url);
        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED
                || statusCode == HttpStatus.SC_ACCEPTED) {
            HttpEntity resEntity = response.getEntity();
            retString = (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
        } else {
            HttpEntity resEntity = response.getEntity();
            throw new AkServerStatusException(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(resEntity, CHARSET));
        }
    } catch (ClientProtocolException cpe) {
        Log.e(TAG, cpe.toString(), cpe);
        throw new AkInvokeException(AkInvokeException.CODE_HTTP_PROTOCOL_ERROR, cpe.toString(), cpe);
    } catch (IOException ioe) {
        Log.e(TAG, ioe.toString(), ioe);
        throw new AkInvokeException(AkInvokeException.CODE_CONNECTION_ERROR, ioe.toString(), ioe);
    }

    Log.v(TAG, "response:" + retString);
    return retString;
}

From source file:org.akita.io.HttpInvoker.java

public static String get(String url, Header[] headers) throws AkServerStatusException, AkInvokeException {
    Log.v(TAG, "get:" + url);
    String retString = null;//from  w ww  . j  av  a2  s  . c  om
    try {
        HttpGet request = new HttpGet(url);
        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED
                || statusCode == HttpStatus.SC_ACCEPTED) {
            HttpEntity resEntity = response.getEntity();
            retString = (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
        } else {
            HttpEntity resEntity = response.getEntity();
            throw new AkServerStatusException(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(resEntity, CHARSET));
        }
    } catch (ClientProtocolException cpe) {
        Log.e(TAG, cpe.toString(), cpe);
        throw new AkInvokeException(AkInvokeException.CODE_HTTP_PROTOCOL_ERROR, cpe.toString(), cpe);
    } catch (IOException ioe) {
        Log.e(TAG, ioe.toString(), ioe);
        throw new AkInvokeException(AkInvokeException.CODE_CONNECTION_ERROR, ioe.toString(), ioe);
    }

    Log.v(TAG, "response:" + retString);
    return retString;
}

From source file:com.alibaba.akita.io.HttpInvoker.java

/**
 * version 1 remoteimageview download impl, use InputStream to decode.
 * @param imgUrl/* w w w. j  a va 2 s .c o  m*/
 * @param inSampleSize
 * @return
 * @throws AkServerStatusException
 * @throws AkInvokeException
 */
public static Bitmap getImageFromUrl(String imgUrl, int inSampleSize)
        throws AkServerStatusException, AkInvokeException {
    Log.v(TAG, "getImageFromUrl:" + imgUrl);
    Bitmap bitmap = null;
    for (int cnt = 0; cnt < NUM_RETRIES; cnt++) {
        try {
            HttpGet request = new HttpGet(imgUrl);
            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED
                    || statusCode == HttpStatus.SC_ACCEPTED) {
                HttpEntity resEntity = response.getEntity();
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    if (inSampleSize > 0 && inSampleSize < 10) {
                        options.inSampleSize = inSampleSize;
                    } else {
                        options.inSampleSize = 0;
                    }
                    InputStream inputStream = resEntity.getContent();

                    // return BitmapFactory.decodeStream(inputStream);
                    // Bug on slow connections, fixed in future release.
                    bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream), null, options);
                } catch (Exception e) {
                    e.printStackTrace(); //TODO no op
                    // no op
                }
                break;
            } else {
                HttpEntity resEntity = response.getEntity();
                throw new AkServerStatusException(response.getStatusLine().getStatusCode(),
                        EntityUtils.toString(resEntity, CHARSET));
            }
        } catch (ClientProtocolException cpe) {
            Log.e(TAG, cpe.toString(), cpe);
            throw new AkInvokeException(AkInvokeException.CODE_HTTP_PROTOCOL_ERROR, cpe.toString(), cpe);
        } catch (IOException ioe) {
            Log.e(TAG, ioe.toString(), ioe);
            throw new AkInvokeException(AkInvokeException.CODE_CONNECTION_ERROR, ioe.toString(), ioe);
        }
    }
    return bitmap;
}

From source file:com.alibaba.akita.io.HttpInvoker.java

/**
 * Vversion 2 remoteimageview download impl, use byte[] to decode.
 * Note: Recommanded to use this method instead of version 1.
 * NUM_RETRIES retry./*from  w  w w .  j a va2  s .  c  o  m*/
 * @param imgUrl
 * @param httpReferer http Referer
 * @return
 * @throws AkServerStatusException
 * @throws AkInvokeException
 */
public static Bitmap getBitmapFromUrl(String imgUrl, String httpReferer, ProgressBar progressBar)
        throws AkServerStatusException, AkInvokeException {
    imgUrl = imgUrl.trim();
    Log.v(TAG, "getBitmapFromUrl:" + imgUrl);

    int timesTried = 1;

    while (timesTried <= NUM_RETRIES) {
        timesTried++;
        try {
            if (progressBar != null) {
                progressBar.setProgress(0);
            }
            HttpGet request = new HttpGet(imgUrl);
            if (httpReferer != null)
                request.addHeader("Referer", httpReferer);
            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED
                    || statusCode == HttpStatus.SC_ACCEPTED) {
                HttpEntity resEntity = response.getEntity();
                InputStream inputStream = resEntity.getContent();

                byte[] imgBytes = retrieveImageData(inputStream, (int) (resEntity.getContentLength()),
                        progressBar);
                if (imgBytes == null) {
                    SystemClock.sleep(DEFAULT_RETRY_SLEEP_TIME);
                    continue;
                }

                Bitmap bm = null;
                try {
                    bm = ImageUtil.decodeSampledBitmapFromByteArray(imgBytes, 0, imgBytes.length, 682, 682);
                } catch (OutOfMemoryError ooe) {
                    Log.e(TAG, ooe.toString(), ooe);
                    return null; // if oom, no need to retry.
                }
                if (bm == null) {
                    SystemClock.sleep(DEFAULT_RETRY_SLEEP_TIME);
                    continue;
                }
                return bm;
            } else {
                HttpEntity resEntity = response.getEntity();
                throw new AkServerStatusException(response.getStatusLine().getStatusCode(),
                        EntityUtils.toString(resEntity, CHARSET));
            }
        } catch (ClientProtocolException cpe) {
            Log.e(TAG, cpe.toString(), cpe);
            throw new AkInvokeException(AkInvokeException.CODE_HTTP_PROTOCOL_ERROR, cpe.toString(), cpe);
        } catch (IOException ioe) {
            Log.e(TAG, ioe.toString(), ioe);
            throw new AkInvokeException(AkInvokeException.CODE_CONNECTION_ERROR, ioe.toString(), ioe);
        } catch (IllegalStateException ise) {
            Log.e(TAG, ise.toString(), ise);
            throw new AkInvokeException(AkInvokeException.CODE_TARGET_HOST_OR_URL_ERROR, ise.toString(), ise);
        } catch (IllegalArgumentException iae) {
            throw new AkInvokeException(AkInvokeException.CODE_TARGET_HOST_OR_URL_ERROR, iae.toString(), iae);
        } catch (Exception e) {
            throw new AkInvokeException(AkInvokeException.CODE_UNKOWN_ERROR, e.toString(), e);
        }

    }

    return null;
}

From source file:com.hichinaschool.flashcards.anki.Feedback.java

/**
 * Posting feedback or error info to the server. This is called from the AsyncTask.
 * /*from  w w  w .  java 2s.c  om*/
 * @param url The url to post the feedback to.
 * @param type The type of the info, eg Feedback.TYPE_CRASH_STACKTRACE.
 * @param feedback For feedback types this is the message. For error/crash types this is the path to the error file.
 * @param groupId A single time generated ID, so that errors/feedback send together can be grouped together.
 * @param index The index of the error in the list
 * @return A Payload file showing success, response code and response message.
 */
public static Payload postFeedback(String url, String type, String feedback, String groupId, int index,
        Application app) {
    Payload result = new Payload(null);

    List<NameValuePair> pairs = null;
    if (!isErrorType(type)) {
        pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("type", type));
        pairs.add(new BasicNameValuePair("groupid", groupId));
        pairs.add(new BasicNameValuePair("index", "0"));
        pairs.add(new BasicNameValuePair("message", feedback));
        addTimestamp(pairs);
    } else {
        pairs = Feedback.extractPairsFromError(type, feedback, groupId, index, app);
        if (pairs == null) {
            result.success = false;
            result.result = null;
        }
    }

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("User-Agent", "AnkiDroid");
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse response = httpClient.execute(httpPost);
        Log.e(AnkiDroidApp.TAG, String.format("Bug report posted to %s", url));

        int respCode = response.getStatusLine().getStatusCode();
        switch (respCode) {
        case 200:
            result.success = true;
            result.returnType = respCode;
            result.result = Utils.convertStreamToString(response.getEntity().getContent());
            // Log.i(AnkiDroidApp.TAG, String.format("postFeedback OK: %s", result.result));
            break;

        default:
            Log.e(AnkiDroidApp.TAG, String.format("postFeedback failure: %d - %s",
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
            result.success = false;
            result.returnType = respCode;
            result.result = response.getStatusLine().getReasonPhrase();
            break;
        }
    } catch (ClientProtocolException ex) {
        Log.e(AnkiDroidApp.TAG, "ClientProtocolException: " + ex.toString());
        result.success = false;
        result.result = ex.toString();
    } catch (IOException ex) {
        Log.e(AnkiDroidApp.TAG, "IOException: " + ex.toString());
        result.success = false;
        result.result = ex.toString();
    }
    return result;
}

From source file:com.ichi2.anki2.Feedback.java

/**
 * Posting feedback or error info to the server. This is called from the AsyncTask.
 * //www.  j a v  a  2 s  . c o  m
 * @param url The url to post the feedback to.
 * @param type The type of the info, eg Feedback.TYPE_CRASH_STACKTRACE.
 * @param feedback For feedback types this is the message. For error/crash types this is the path to the error file.
 * @param groupId A single time generated ID, so that errors/feedback send together can be grouped together.
 * @param index The index of the error in the list
 * @return A Payload file showing success, response code and response message.
 */
public static Payload postFeedback(String url, String type, String feedback, String groupId, int index,
        Application app) {
    Payload result = new Payload(null);

    List<NameValuePair> pairs = null;
    if (!isErrorType(type)) {
        pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("type", type));
        pairs.add(new BasicNameValuePair("groupid", groupId));
        pairs.add(new BasicNameValuePair("index", "0"));
        pairs.add(new BasicNameValuePair("message", feedback));
        addTimestamp(pairs);
    } else {
        pairs = Feedback.extractPairsFromError(type, feedback, groupId, index, app);
        if (pairs == null) {
            result.success = false;
            result.result = null;
        }
    }

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("User-Agent", "AnkiDroid");
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse response = httpClient.execute(httpPost);
        Log.e(AnkiDroidApp.TAG, String.format("Bug report posted to %s", url));

        int respCode = response.getStatusLine().getStatusCode();
        switch (respCode) {
        case 200:
            result.success = true;
            result.returnType = respCode;
            result.result = Utils.convertStreamToString(response.getEntity().getContent());
            Log.i(AnkiDroidApp.TAG, String.format("postFeedback OK: %s", result.result));
            break;

        default:
            Log.e(AnkiDroidApp.TAG, String.format("postFeedback failure: %d - %s",
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
            result.success = false;
            result.returnType = respCode;
            result.result = response.getStatusLine().getReasonPhrase();
            break;
        }
    } catch (ClientProtocolException ex) {
        Log.e(AnkiDroidApp.TAG, "ClientProtocolException: " + ex.toString());
        result.success = false;
        result.result = ex.toString();
    } catch (IOException ex) {
        Log.e(AnkiDroidApp.TAG, "IOException: " + ex.toString());
        result.success = false;
        result.result = ex.toString();
    }
    return result;
}