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:de.dan_nrw.android.followerstat.dao.folllowers.TwitterFollowerDAO.java

@Override
public Follower[] getFollowers(String userName)
        throws TwitterUserAccountNotFoundException, TwitterRequestException {
    try {//ww  w.j  a  v a  2s  .com
        String json = this.sendRequest(
                URI.create(String.format("http://twitter.com/statuses/followers/%s.json", userName)),
                new StringResponseHandler(), true);

        JSONArray jsonArray = new JSONArray(json);

        List<Follower> followers = new ArrayList<Follower>();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            followers.add(new Follower(jsonObject.getString("screen_name"),
                    URI.create(jsonObject.getString("profile_image_url"))));
        }

        return followers.toArray(new Follower[followers.size()]);
    } catch (ClientProtocolException ex) {
        throw new TwitterRequestException(ex);
    } catch (SecurityException ex) {
        throw new TwitterAuthException(ex.getCause());
    } catch (IOException ex) {
        if (ex.getMessage().equals("404")) {
            throw new TwitterUserAccountNotFoundException();
        }

        throw new TwitterRequestException(ex);
    } catch (JSONException ex) {
        throw new TwitterResponseParsingException(ex);
    } catch (OAuthExpectationFailedException ex) {
        throw new TwitterAuthException(ex);
    } catch (OAuthException ex) {
        throw new TwitterAuthException(ex);
    }
}

From source file:com.juanojfp.gcmsample.MainActivity.java

public String registerInServer(String token) {

    String imei = Build.SERIAL;//from   www. j av a2s  .c  o m
    String model = Build.MANUFACTURER + ":" + Build.MODEL;
    String sdk = Build.VERSION.SDK + ":" + Build.VERSION.RELEASE;

    Log.e("RegisterInServer", "Imei: " + imei);

    HttpClient client = new DefaultHttpClient();

    StringBuilder peticion = new StringBuilder();
    peticion.append(URL_TO_SERVER).append(MODULE_DEVICE).append(COMMAND_REGISTER);

    Log.e("Peticion:", peticion.toString());

    HttpPost method = new HttpPost(peticion.toString());
    String msgServer;

    try {
        List<NameValuePair> nvp = new ArrayList<NameValuePair>();
        nvp.add(new BasicNameValuePair(PARAM_C2DM_DEVICE_TOKEN, token));
        nvp.add(new BasicNameValuePair(PARAM_C2DM_DEVICE_IMEI, imei));
        nvp.add(new BasicNameValuePair(PARAM_C2DM_DEVICE_MODEL, model));
        nvp.add(new BasicNameValuePair(PARAM_C2DM_DEVICE_SDK, sdk));

        for (NameValuePair v : nvp)
            Log.e("Parametro", v.getName() + ":" + v.getValue());

        method.setEntity(new UrlEncodedFormEntity(nvp, HTTP.UTF_8));

        HttpResponse response = client.execute(method);
        //Respuestas
        //{'message':'username', 'id':idUser, 'code':0}
        //{'message':'Token perdido', 'code':1}
        JSONObject json = new JSONObject(input2String(response.getEntity().getContent()));
        String msg = json.getString(PARAM_C2DM_DEVICE_MESSAGE);
        int id = json.getInt(PARAM_C2DM_DEVICE_MESSAGE_ID);
        int code = json.getInt(PARAM_C2DM_DEVICE_MESSAGE_CODE);

        msgServer = id + ":" + msg + ":" + code;

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        msgServer = e.getMessage();
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        msgServer = e.getMessage();
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        msgServer = e.getMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        msgServer = e.getMessage();
        e.printStackTrace();
    }

    Log.e("Serever Response", msgServer);
    return msgServer;
}

From source file:es.uma.lcc.tasks.DecryptionRequestTask.java

public Void doInBackground(Void... parameters) {
    if (mPicId == null) {
        mDecodedBmp = BitmapFactory.decodeFile(mSrc);
    } else {//w w w . j  av a2  s .c om
        DefaultHttpClient httpclient = new DefaultHttpClient();
        final HttpParams params = new BasicHttpParams();
        HttpClientParams.setRedirecting(params, false);
        httpclient.setParams(params);
        String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_READPERMISSIONS + "&"
                + QUERYSTRING_PICTUREID + "=" + mPicId;
        HttpGet httpget = new HttpGet(target);

        while (mCookie == null) // loop until authentication finishes, if necessary
            mCookie = mMainActivity.getCurrentCookie();

        httpget.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue());
        System.out.println("Cookie in header: " + mMainActivity.getCurrentCookie().getValue());
        try {
            HttpResponse response = httpclient.execute(httpget);

            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() != 200) {
                mConnectionSucceeded = false;
                throw new IOException("Invalid response from server: " + status.toString());
            }

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = entity.getContent();
                ByteArrayOutputStream content = new ByteArrayOutputStream();

                // Read response into a buffered stream
                int readBytes = 0;
                byte[] sBuffer = new byte[256];
                while ((readBytes = inputStream.read(sBuffer)) != -1) {
                    content.write(sBuffer, 0, readBytes);
                }
                String result = new String(content.toByteArray());

                try {
                    JSONArray jsonArray = new JSONArray(result);
                    JSONObject jsonObj;
                    if (jsonArray.length() == 0) {
                        // should never happen
                        Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server");
                    } else {
                        // Elements in a JSONArray keep their order
                        JSONObject successState = jsonArray.getJSONObject(0);
                        if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) {
                            if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) {
                                mIsAuthError = true;
                                Log.e(APP_TAG, LOG_ERROR + ": Server found an auth error: "
                                        + successState.get(JSON_REASON));
                            } else {
                                Log.e(APP_TAG, LOG_ERROR + ": Server found an error: "
                                        + successState.get(JSON_REASON));
                            }
                        } else {
                            mSquareNum = jsonArray.length() - 1;
                            mHorizStarts = new int[mSquareNum];
                            mHorizEnds = new int[mSquareNum];
                            mVertStarts = new int[mSquareNum];
                            mVertEnds = new int[mSquareNum];
                            mKeys = new String[mSquareNum];
                            for (int i = 0; i < mSquareNum; i++) {
                                jsonObj = jsonArray.getJSONObject(i + 1);
                                mHorizStarts[i] = jsonObj.getInt(JSON_HSTART);
                                mHorizEnds[i] = jsonObj.getInt(JSON_HEND);
                                mVertStarts[i] = jsonObj.getInt(JSON_VSTART);
                                mVertEnds[i] = jsonObj.getInt(JSON_VEND);
                                mKeys[i] = jsonObj.getString(JSON_KEY);
                            }
                            publishProgress(10);
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true; // get dimensions without reloading the image
                            BitmapFactory.decodeFile(mSrc, options);
                            mWidth = options.outWidth;
                            mHeight = options.outHeight;
                            mDecodedBmp = Bitmap.createBitmap(options.outWidth, options.outHeight,
                                    Config.ARGB_8888);

                            if (mSquareNum == 0) {
                                mDecodedBmp = BitmapFactory.decodeFile(mSrc);
                            } else {
                                mHasFoundKeys = true;
                                byte[] pixels = MainActivity.decodeWrapperRegions(mSrc, mSquareNum,
                                        mHorizStarts, mHorizEnds, mVertStarts, mVertEnds, mKeys, mPicId);

                                /* Native side returns each pixel as an RGBA quadruplet, with
                                 each a C unsigned byte ([0,255]). However, Java reads those
                                 as signed bytes ([-128, 127]) in two's complement.
                                 We mask them with 0xFF to ensure most significant bits set to 0,
                                 therefore interpreting them as their positive (unsigned) value.
                                 Furthermore, Java functions take pixels in ARGB (and not RGBA),
                                 so we manually re-order them */
                                int baseIndex;
                                for (int i = 0; i < mWidth; i++) {
                                    for (int j = 0; j < mHeight; j++) {
                                        baseIndex = 4 * (j * mWidth + i);
                                        mDecodedBmp.setPixel(i, j,
                                                Color.argb(pixels[baseIndex + 3] & 0xff,
                                                        pixels[baseIndex] & 0xff, pixels[baseIndex + 1] & 0xff,
                                                        pixels[baseIndex + 2] & 0xff));
                                    }
                                }
                            }
                        }
                    }
                } catch (JSONException jsonEx) {
                    Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server");
                    mSquareNum = 0;
                }
            }
        } catch (ClientProtocolException e) {
            mConnectionSucceeded = false;
            Log.e(APP_TAG, LOG_ERROR + ": " + e.getMessage());
        } catch (IOException e) {
            mConnectionSucceeded = false;
            Log.e(APP_TAG, LOG_ERROR + ": " + e.getMessage());
        }
    }
    return null;
}

From source file:org.openhmis.oauth2.OAuth2Utils.java

/**
 * /*from   w w w  .j  a va  2  s.  co m*/
 * @param oauthDetails
 * @return
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public String getAccessToken(OAuth2Details oauthDetails) {
    HttpPost post = new HttpPost(oauthDetails.getAuthenticationServerUrl());
    String clientId = oauthDetails.getClientId();
    String clientSecret = oauthDetails.getClientSecret();
    String scope = oauthDetails.getScope();

    List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
    parametersBody.add(new BasicNameValuePair(OAuthConstants.GRANT_TYPE, oauthDetails.getGrantType()));

    parametersBody.add(new BasicNameValuePair(OAuthConstants.USERNAME, oauthDetails.getUsername()));

    parametersBody.add(new BasicNameValuePair(OAuthConstants.PASSWORD, oauthDetails.getPassword()));

    if (isValid(clientId)) {
        parametersBody.add(new BasicNameValuePair(OAuthConstants.CLIENT_ID, oauthDetails.getClientId()));
    }
    if (isValid(clientSecret)) {
        parametersBody
                .add(new BasicNameValuePair(OAuthConstants.CLIENT_SECRET, oauthDetails.getClientSecret()));
    }

    if (isValid(scope)) {
        parametersBody.add(new BasicNameValuePair(OAuthConstants.SCOPE, oauthDetails.getScope()));
    }

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = null;
    String accessToken = null;
    try {
        post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
        response = httpClient.execute(post);
        int code = response.getStatusLine().getStatusCode();
        if (code >= 400) {
            log.debug("Authorization server expects Basic authentication");
            post.addHeader(OAuthConstants.AUTHORIZATION,
                    getBasicAuthorizationHeader(oauthDetails.getUsername(), oauthDetails.getPassword()));
            post.releaseConnection();
            response = httpClient.execute(post);
            code = response.getStatusLine().getStatusCode();
            if (code >= 400) {
                log.debug("Retry with client credentials");
                post.removeHeaders(OAuthConstants.AUTHORIZATION);
                post.addHeader(OAuthConstants.AUTHORIZATION, getBasicAuthorizationHeader(
                        oauthDetails.getClientId(), oauthDetails.getClientSecret()));
                post.releaseConnection();
                response = httpClient.execute(post);
                if (code >= 400) {
                    throw new RuntimeException(
                            "Could not retrieve access token for user: " + oauthDetails.getUsername());
                }
            }
        }
        Map<String, String> map = handleResponse(response);
        accessToken = map.get(OAuthConstants.ACCESS_TOKEN);
    } catch (ClientProtocolException cpe) {
        cpe.getStackTrace(); // will remove after testing
        log.debug(cpe.getMessage());
    } catch (IOException ioe) {
        ioe.getStackTrace(); // will remove after testing
        log.debug(ioe.getMessage());
    }
    return accessToken;
}

From source file:com.mnxfst.testing.client.TSClientPlanExecCallable.java

/**
 * @see java.util.concurrent.Callable#call()
 *///from   w w w  .j a va 2s .  c om
@SuppressWarnings("unused")
public NameValuePair call() throws Exception {

    InputStream ptestServerInputStream = null;
    try {
        //         HttpResponse response = httpClient.execute(httpHost, getMethod);
        HttpResponse response = httpClient.execute(httpHost, postMethod);
        ptestServerInputStream = response.getEntity().getContent();

        XPath xpath = XPathFactory.newInstance().newXPath();
        Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(ptestServerInputStream);
        if (response == null)
            throw new TSClientExecutionException(
                    "No response document received from " + httpHost.getHostName());

        // fetch root node
        Node rootNode = responseDoc.getFirstChild();
        if (rootNode == null)
            throw new TSClientExecutionException(
                    "No valid root node found in document received from " + httpHost.getHostName());
        if (rootNode.getNodeName() == null || !rootNode.getNodeName().equalsIgnoreCase(TEST_EXEC_RESPONSE_ROOT))
            throw new TSClientExecutionException(
                    "No valid root node found in document received from " + httpHost.getHostName());

        int responseCode = parseResponseCode(rootNode, xpath);
        switch (responseCode) {
        case RESPONSE_CODE_EXECUTION_STARTED: {
            String responseIdentifier = parseResultIdentifier(rootNode, xpath);
            return new BasicNameValuePair(httpHost.getHostName(), responseIdentifier);
        }
        case RESPONSE_CODE_ERROR: {
            List<Long> errorCodes = parseErrorCodes(rootNode, xpath);
            StringBuffer codes = new StringBuffer();
            for (Iterator<Long> iter = errorCodes.iterator(); iter.hasNext();) {
                codes.append(iter.next());
                if (iter.hasNext())
                    codes.append(",");
            }

            throw new TSClientExecutionException("Failed to execute test plan on " + httpHost.getHostName()
                    + ":" + httpHost.getPort() + ". Error codes: " + codes.toString());
        }
        default: {
            throw new TSClientExecutionException("Unexpected response code '" + responseCode
                    + "' received from " + httpHost.getHostName() + ":" + httpHost.getPort());
        }
        }

    } catch (ClientProtocolException e) {
        throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":"
                + httpHost.getPort() + "/" + postMethod.getURI() + ". Error: " + e.getMessage());
    } catch (IOException e) {
        throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":"
                + httpHost.getPort() + "/" + postMethod.getURI() + ". Error: " + e.getMessage());
    } finally {
        if (ptestServerInputStream != null) {
            try {
                ptestServerInputStream.close();
                httpClient.getConnectionManager().shutdown();

            } catch (Exception e) {
                System.out.println("Failed to close ptest-server connection");
            }
        }
    }
}

From source file:com.ushahidi.swiftriver.core.api.auth.crowdmapid.CrowdmapIDClient.java

/**
 * Internal helper method for sending request to the CrowdmapID server
 * /*from w w  w.  java 2s  .c o  m*/
 * @param apiRequest
 * @param requestParams
 * @return
 */
private Map<String, Object> executeApiRequest(CrowdmapIDRequestType apiRequest,
        List<NameValuePair> requestParams) {
    // Base URI for the request
    String baseURIStr = getBaseRequestUrl(apiRequest);
    Map<String, Object> responseMap = new HashMap<String, Object>();

    // Build the request and set parameters
    HttpPost httpPost = new HttpPost(baseURIStr);
    requestParams.add(new BasicNameValuePair(this.apiKeyParamName, this.apiKey));

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(requestParams, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    String apiResponse = null;

    // Execute the request
    try {
        HttpResponse httpResponse = httpClient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        apiResponse = readApiResponse(httpResponse);
        if (statusCode != 200) {
            logger.error("The server returned status {} - {}", statusCode, apiResponse);
            return responseMap;
        }

    } catch (ClientProtocolException e) {
        logger.error("An error occurred when processing request: {} - {}", this.serverURL, e.getMessage());
    } catch (IOException e) {
        logger.error("An error occurred when reading the response from the server: {} - {}", this.serverURL,
                e.getMessage());
    }

    // Deserialize the response into a java.util.Map
    if (apiResponse != null) {
        try {
            responseMap = jacksonObjectMapper.readValue(apiResponse, new TypeReference<Map<String, Object>>() {
            });
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Check for the status
    if (!responseMap.isEmpty()) {
        Boolean status = (Boolean) responseMap.get("success");
        if (!status) {
            logger.error("The API returned the following error message: {}", responseMap.get("error"));

            // Clear all mappings and return an empty map
            responseMap.clear();
        }
    }
    return responseMap;
}

From source file:net.evecom.androidecssp.activity.TaskResponseAddActivity.java

private void postdata(final HashMap<String, String> entity) {
    new Thread(new Runnable() {
        @Override/*w w  w .j  av  a2s.c o  m*/
        public void run() {
            Message message = new Message();
            try {
                saveResult = connServerForResultPost("jfs/ecssp/mobile/taskresponseCtr/taskResponseAdd",
                        entity);
            } catch (ClientProtocolException e) {
                message.what = MESSAGETYPE_02;
                Log.e("mars", e.getMessage());
            } catch (IOException e) {
                message.what = MESSAGETYPE_02;
                Log.e("mars", e.getMessage());
            }
            if (saveResult.length() > 0) {
                message.what = MESSAGETYPE_01;
                String responseid = "";
                try {
                    TaskResponseInfo taskResponseInfo = getTaskResponseInfo(saveResult);
                    if (null != taskResponseInfo) {
                        responseid = taskResponseInfo.getId();
                    }
                } catch (JSONException e) {
                    Log.e("mars", e.getMessage());
                }
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("taskresponseId", responseid);
                postImage(hashMap, fileList, "jfs/ecssp/mobile/taskresponseCtr/taskResponseFileSave");
            } else {
                message.what = MESSAGETYPE_02;
            }
            Log.v("mars", saveResult);
            saveHandler.sendMessage(message);
        }
    }).start();

}

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

protected <T> T call(HttpRequestBase method, ResponseHandler<? extends T> responseHandler, boolean isBasic) {
    if (isBasic) {
        initHttpClient();//from  w  w  w.  j a  v a 2  s  .  c  om
    } else {
        initOAuthHttpClient();
    }
    T response = null;
    try {
        response = httpclient.execute(targetHost, method, responseHandler, localcontext);
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        closeHttpClientConnection();
    }
    return response;
}

From source file:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Logout of the EZID service session./*w  ww  .  j  av  a  2 s . c  om*/
 * 
 * @throws EzidException
 */
public void logout() throws EzidException {

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    String url = this.getEzidUrl("/logout");
    HttpGet httpGet = new HttpGet(url);
    String entityString = null;
    Integer statusCode = null;

    // Set header content
    if (this.sessionId != null) {
        httpGet.setHeader("Cookie", "sessionid=" + this.sessionId);
    }

    try {

        HttpResponse httpResponse = httpClient.execute(httpGet);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        HttpEntity httpEntity = httpResponse.getEntity();
        entityString = EntityUtils.toString(httpEntity);

    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    if (statusCode != HttpStatus.SC_OK) {
        String gripe = "Failed to logout of EZID cleanly.";
        throw new EzidException(gripe);
    }

    logger.info("logout: " + entityString);

}

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

private <T> T callRest(HttpRequestBase method, boolean isBasic, Class<T> t) {
    if (isBasic) {
        initHttpClient();/* w ww . j a v a2s .  c om*/
    } else {
        initOAuthHttpClient();
    }
    HttpResponse response = null;
    T result = null;
    try {
        response = httpclient.execute(method);
        checkResponseStatus(response);
        JSONObject json = JSONObject.fromObject(parseReponseToString(response));
        result = (T) json.toBean(json, t);
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        closeHttpClientConnection();
    }
    return result;
}