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:custom.application.search.java

private Document execute(String query, int start) throws ApplicationException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpget;//from  w  w  w.j  av  a  2 s.  c o m
    try {
        httpget = new HttpGet(createRequestString(query, start == 0 ? 1 : start));
        httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");

        HttpResponse response = httpClient.execute(httpget);
        InputStream instream = response.getEntity().getContent();

        Document document = new Document();
        document.load(instream);
        if (document.getRoot().getElementsByTagName("errors").size() > 0 && i++ < ids.length - 1) {
            CUSTOM_SEARCH_ENGINE_ID = ids[i];
            API_KEY = keys[i];
            System.out.println("Using:" + ids[i]);

            httpget = new HttpGet(createRequestString(query, start == 0 ? 1 : start));
            httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");

            response = httpClient.execute(httpget);
            instream = response.getEntity().getContent();

            document.load(instream);
        }

        return document;
    } catch (ClientProtocolException e) {
        throw new ApplicationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new ApplicationException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new ApplicationException(e.getMessage(), e);
    }

}

From source file:org.mythdroid.util.UpdateService.java

private void updateMythDroid(String ver, String url) {

    LogUtil.debug("Fetching APK from " + url); //$NON-NLS-1$

    HttpFetcher fetcher = null;//from w  w w .j  a  v a2s .c  o  m
    try {
        fetcher = new HttpFetcher(url, false);
    } catch (ClientProtocolException e) {
        ErrUtil.logErr(e);
        notify("MythDroid" + Messages.getString("UpdateService.2"), //$NON-NLS-1$ //$NON-NLS-2$
                e.getMessage());
        return;
    } catch (IOException e) {
        ErrUtil.logErr(e);
        notify("MythDroid" + Messages.getString("UpdateService.2"), //$NON-NLS-1$ //$NON-NLS-2$
                e.getMessage());
        return;
    }

    final File storage = Environment.getExternalStorageDirectory();
    final File outputFile = new File(storage.getAbsolutePath() + '/' + "Download", //$NON-NLS-1$
            "MythDroid-" + ver + ".apk" //$NON-NLS-1$ //$NON-NLS-2$
    );

    LogUtil.debug("Saving to " + outputFile.getAbsolutePath()); //$NON-NLS-1$

    FileOutputStream outputStream;
    try {
        outputStream = new FileOutputStream(outputFile);
    } catch (FileNotFoundException e) {
        ErrUtil.logErr("SDCard is unavailable"); //$NON-NLS-1$
        notify("MythDroid" + Messages.getString("UpdateService.2"), //$NON-NLS-1$ //$NON-NLS-2$
                Messages.getString("UpdateService.4") //$NON-NLS-1$
        );
        return;
    }

    try {
        fetcher.writeTo(outputStream);
    } catch (IOException e) {
        ErrUtil.logErr(e);
        notify("MythDroid" + Messages.getString("UpdateService.2"), //$NON-NLS-1$ //$NON-NLS-2$
                e.getMessage());
        return;
    }

    LogUtil.debug("Download successful, installing..."); //$NON-NLS-1$

    final Intent installIntent = new Intent(Intent.ACTION_VIEW);
    installIntent.setDataAndType(Uri.fromFile(outputFile), "application/vnd.android.package-archive" //$NON-NLS-1$
    );
    installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(installIntent);

}

From source file:com.microsoft.live.ApiRequest.java

/**
 * Performs the Http Request and returns the response from the server
 *
 * @return an instance of ResponseType from the server
 * @throws LiveOperationException if there was an error executing the HttpRequest
 *//*from  w  w w  .  j  a  v  a  2 s.c o m*/
public ResponseType execute() throws LiveOperationException {
    // Let subclass decide which type of request to instantiate
    HttpUriRequest request = this.createHttpRequest();

    request.addHeader(LIVE_LIBRARY_HEADER);

    if (this.session.willExpireInSecs(SESSION_REFRESH_BUFFER_SECS)) {
        this.session.refresh();
    }

    // if the session will soon expire, try to send the request without a token.
    // the request *may* not need the token, let's give it a try rather than
    // risk a request with an invalid token.
    if (!this.session.willExpireInSecs(SESSION_TOKEN_SEND_BUFFER_SECS)) {
        request.addHeader(createAuthroizationHeader(this.session));
    }

    try {
        HttpResponse response = this.client.execute(request);

        for (Observer observer : this.observers) {
            observer.onComplete(response);
        }

        return this.responseHandler.handleResponse(response);
    } catch (ClientProtocolException e) {
        throw new LiveOperationException(ErrorMessages.SERVER_ERROR, e);
    } catch (IOException e) {
        // The IOException could contain a JSON object body
        // (see InputStreamResponseHandler.java). If it does,
        // we want to throw an exception with its message. If it does not, we want to wrap
        // the IOException.
        try {
            new JSONObject(e.getMessage());
            throw new LiveOperationException(e.getMessage());
        } catch (JSONException jsonException) {
            throw new LiveOperationException(ErrorMessages.SERVER_ERROR, e);
        }
    }
}

From source file:com.projecttango.experiments.basictango_button.MainActivity.java

private void setTangoListeners() {
    // Select coordinate frame pairs
    ArrayList<TangoCoordinateFramePair> framePairs = new ArrayList<TangoCoordinateFramePair>();
    framePairs.add(new TangoCoordinateFramePair(TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
            TangoPoseData.COORDINATE_FRAME_DEVICE));

    // Add a listener for Tango pose data
    mTango.connectListener(framePairs, new OnTangoUpdateListener() {

        @SuppressLint("DefaultLocale")
        @Override//from w  w  w. j av  a 2s  .  c  om
        public void onPoseAvailable(TangoPoseData pose) {
            if (mIsProcessing) {
                Log.i(TAG, "Processing UI");
                return;
            }
            mIsProcessing = true;

            // Format Translation and Rotation data
            final String translationMsg = String.format(sTranslationFormat, pose.translation[0],
                    pose.translation[1], pose.translation[2]);
            final String rotationMsg = String.format(sRotationFormat, pose.rotation[0], pose.rotation[1],
                    pose.rotation[2], pose.rotation[3]);

            // Output to LogCat for testing purposes
            // String logMsg = translationMsg + " | " + rotationMsg + " | " + pose.timestamp;
            // Log.i(TAG, logMsg);

            //If button returns true
            if (isOn) {
                try {
                    timestamp = pose.timestamp; //get timestamp data

                    //Initializes HTTP POST request
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("http://10.101.102.123/datapoint");
                    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
                    nameValuePair.add(new BasicNameValuePair("timestamp", timestamp + ""));
                    nameValuePair.add(new BasicNameValuePair("translation", translationMsg));
                    nameValuePair.add(new BasicNameValuePair("rotation", rotationMsg));

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

                    try {
                        //Send Request
                        HttpResponse response = httpclient.execute(httpPost);
                        // write response to log
                        Log.d("Http Post Response:", response.toString());
                    } catch (ClientProtocolException e) { // Catch a few different Exceptions
                        // Log exception
                        e.printStackTrace();
                    } catch (IOException e) {
                        // Log exception
                        e.printStackTrace();
                        Log.i(TAG, e.getMessage());
                    }

                    // HttpResponse response = httpclient.execute(new HttpGet("http://localhost:1234/send-data"));
                } catch (Exception exception) {
                    Log.i(TAG, exception.getMessage());
                }
            }

            // Display data in TextViews. This must be done inside a
            // runOnUiThread call because
            // it affects the UI, which will cause an error if performed
            // from the Tango
            // service thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.i(TAG, "ISON = " + isOn);

                    //If Button returns True
                    if (isOn) {
                        mTranslationTextView.setText("Translation: " + translationMsg);
                        mRotationTextView.setText("Rotation: " + rotationMsg);
                        mtimestamp.setText("Timestamp: " + timestamp);
                        mUuid.setText("UUID: " + uuid);
                    }
                    mIsProcessing = false;

                }
            });
        }

        @Override
        public void onXyzIjAvailable(TangoXyzIjData arg0) {
            // Ignoring XyzIj data
        }

        @Override
        public void onTangoEvent(TangoEvent arg0) {
            // Ignoring TangoEvents
        }

        @Override
        public void onFrameAvailable(int arg0) {
            // Ignoring onFrameAvailable Events

        }

    });
}

From source file:com.projecttango.experiments.basictango_button.RestartActivity.java

private void setTangoListeners() {
    Toast.makeText(this, "O_O!" + isOn, Toast.LENGTH_SHORT).show();
    // Select coordinate frame pairs
    ArrayList<TangoCoordinateFramePair> framePairs = new ArrayList<TangoCoordinateFramePair>();
    framePairs.add(new TangoCoordinateFramePair(TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
            TangoPoseData.COORDINATE_FRAME_DEVICE));

    // Add a listener for Tango pose data
    mTango.connectListener(framePairs, new OnTangoUpdateListener() {

        @SuppressLint("DefaultLocale")
        @Override/*from   w w w. ja  va2  s .  c  o  m*/
        public void onPoseAvailable(TangoPoseData pose) {
            if (mIsProcessing) {
                Log.i(TAG, "Processing UI");
                return;
            }
            mIsProcessing = true;

            // Format Translation and Rotation data
            final String translationMsg = String.format(sTranslationFormat, pose.translation[0],
                    pose.translation[1], pose.translation[2]);
            final String rotationMsg = String.format(sRotationFormat, pose.rotation[0], pose.rotation[1],
                    pose.rotation[2], pose.rotation[3]);

            // Output to LogCat for testing purposes
            // String logMsg = translationMsg + " | " + rotationMsg + " | " + pose.timestamp;
            // Log.i(TAG, logMsg);

            //If button returns true
            if (isOn) {
                try {
                    timestamp = pose.timestamp; //get timestamp data

                    //Initializes HTTP POST request
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("http://10.101.102.123/datapoint");
                    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
                    nameValuePair.add(new BasicNameValuePair("timestamp", timestamp + ""));
                    nameValuePair.add(new BasicNameValuePair("translation", translationMsg));
                    nameValuePair.add(new BasicNameValuePair("rotation", rotationMsg));

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

                    try {
                        //Send Request
                        HttpResponse response = httpclient.execute(httpPost);
                        // write response to log
                        Log.d("Http Post Response:", response.toString());
                    } catch (ClientProtocolException e) { // Catch a few different Exceptions
                        // Log exception
                        e.printStackTrace();
                    } catch (IOException e) {
                        // Log exception
                        e.printStackTrace();
                        Log.i(TAG, e.getMessage());
                    }

                    // HttpResponse response = httpclient.execute(new HttpGet("http://localhost:1234/send-data"));
                } catch (Exception exception) {
                    Log.i(TAG, exception.getMessage());
                }
            }

            // Display data in TextViews. This must be done inside a
            // runOnUiThread call because
            // it affects the UI, which will cause an error if performed
            // from the Tango
            // service thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.i(TAG, "ISON = " + isOn);

                    //If Button returns True
                    if (isOn) {

                        mTranslationTextView.setText("Translation: " + translationMsg);
                        mRotationTextView.setText("Rotation: " + rotationMsg);
                        mtimestamp.setText("Timestamp: " + timestamp);
                        mUuid.setText("UUID: " + uuid);
                    }
                    mIsProcessing = false;

                }
            });
        }

        @Override
        public void onXyzIjAvailable(TangoXyzIjData arg0) {
            // Ignoring XyzIj data
        }

        @Override
        public void onTangoEvent(TangoEvent arg0) {
            // Ignoring TangoEvents
        }

        @Override
        public void onFrameAvailable(int arg0) {
            // Ignoring onFrameAvailable Events

        }

    });
}

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

private HttpEntity httpPost(String url, MultipartEntity mpEntity)
        throws NetworkDownException, HttpPostException {
    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);// w  w w .j ava2 s  .  c  om

    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(mpEntity);

    try {
        if (!NetworkUtil.isOnline(mContext))
            throw new NetworkDownException();
        log(TAG, "executing request " + httppost.getRequestLine());
        HttpResponse response = mHttpclient.execute(httppost);
        log(TAG, response.getStatusLine().toString());
        HttpEntity result = response.getEntity();
        if (response != null) {
            log(TAG, EntityUtils.toString(result));
            result.consumeContent();
        }
        mHttpclient.getConnectionManager().shutdown();
        return result;

    } catch (ClientProtocolException e) {
        mHttpclient.getConnectionManager().shutdown();

        throw new HttpPostException(e.getMessage());

    } catch (IOException e) {
        mHttpclient.getConnectionManager().shutdown();
        throw new HttpPostException(e.getMessage());

    }
}

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

/**
 * //from www .j ava 2s  .c o m
 *   
 * 
 * @author Mars zhang
 * @created 2015-12-11 9:40:22
 * @param postUrl
 * @param dictkey
 * @param statehashmap
 */
protected void getLikeDict(final String postUrl, final HashMap<String, String> entityMap,
        final HashMap<String, String> statehashmap) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String result = connServerForResultPost(postUrl, entityMap);
                List<BaseModel> baseModels = getObjsInfo(result);
                for (int i = 0; i < baseModels.size(); i++) {
                    statehashmap.put(baseModels.get(i).get("name") + "",
                            baseModels.get(i).get("dictvalue") + "");
                }
            } 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 ww .j a v a  2  s . c  om*/
 *  
 * 
 * @author Mars zhang
 * @created 2015-11-25 2:08:51
 * @param dictkey
 * @param statehashmap
 */
protected void getDict(final String dictkey, final HashMap<String, String> statehashmap) {
    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);
                for (int i = 0; i < baseModels.size(); i++) {
                    statehashmap.put(baseModels.get(i).get("name") + "",
                            baseModels.get(i).get("dictvalue") + "");
                }
            } 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:info.ajaxplorer.client.http.RestRequest.java

private HttpResponse issueRequest(URI uri, Map<String, String> postParameters, File file, String fileName,
        AjxpFileBody fileBody) throws Exception {
    URI originalUri = new URI(uri.toString());
    if (RestStateHolder.getInstance().getSECURE_TOKEN() != null) {
        uri = new URI(
                uri.toString().concat("&secure_token=" + RestStateHolder.getInstance().getSECURE_TOKEN()));
    }/*w w w  .  ja  v a  2  s  .  c o  m*/
    //Log.d("RestRequest", "Issuing request : " + uri.toString());
    HttpResponse response = null;
    try {
        HttpRequestBase request;

        if (postParameters != null || file != null) {
            request = new HttpPost();
            if (file != null) {

                if (fileBody == null) {
                    if (fileName == null)
                        fileName = file.getName();
                    fileBody = new AjxpFileBody(file, fileName);
                    ProgressListener origPL = this.uploadListener;
                    Map<String, String> caps = RestStateHolder.getInstance().getServer()
                            .getRemoteCapacities(this);
                    this.uploadListener = origPL;
                    int maxUpload = 0;
                    if (caps != null && caps.containsKey(Server.capacity_UPLOAD_LIMIT))
                        maxUpload = new Integer(caps.get(Server.capacity_UPLOAD_LIMIT));
                    maxUpload = Math.min(maxUpload, 60000000);
                    if (maxUpload > 0 && maxUpload < file.length()) {
                        fileBody.chunkIntoPieces(maxUpload);
                        if (uploadListener != null) {
                            uploadListener.partTransferred(fileBody.getCurrentIndex(),
                                    fileBody.getTotalChunks());
                        }
                    }
                } else {
                    if (uploadListener != null) {
                        uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks());
                    }
                }
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("userfile_0", fileBody);

                if (fileName != null && !EncodingUtils
                        .getAsciiString(EncodingUtils.getBytes(fileName, "US-ASCII")).equals(fileName)) {
                    reqEntity.addPart("urlencoded_filename",
                            new StringBody(java.net.URLEncoder.encode(fileName, "UTF-8")));
                }
                if (fileBody != null && !fileBody.getFilename().equals(fileBody.getRootFilename())) {
                    reqEntity.addPart("appendto_urlencoded_part",
                            new StringBody(java.net.URLEncoder.encode(fileBody.getRootFilename(), "UTF-8")));
                }
                if (postParameters != null) {
                    Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> entry = it.next();
                        reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
                    }
                }
                if (uploadListener != null) {
                    CountingMultipartRequestEntity countingEntity = new CountingMultipartRequestEntity(
                            reqEntity, uploadListener);
                    ((HttpPost) request).setEntity(countingEntity);
                } else {
                    ((HttpPost) request).setEntity(reqEntity);
                }
            } else {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
                Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
        } else {
            request = new HttpGet();
        }

        request.setURI(uri);
        if (this.httpUser.length() > 0 && this.httpPassword.length() > 0) {
            request.addHeader("Ajxp-Force-Login", "true");
        }
        response = httpClient.executeInContext(request);
        if (isAuthenticationRequested(response)) {
            sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_REFRESHING_AUTH);
            this.discardResponse(response);
            this.authenticate();
            if (loginStateChanged) {
                // RELOAD
                loginStateChanged = false;
                sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_LOADING_DATA);
                if (fileBody != null)
                    fileBody.resetChunkIndex();
                return this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
            }
        } else if (fileBody != null && fileBody.isChunked() && !fileBody.allChunksUploaded()) {
            this.discardResponse(response);
            this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
        }
    } catch (ClientProtocolException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (AuthenticationException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        throw e;
    } catch (Exception e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } finally {
        uploadListener = null;
    }
    return response;
}

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

public void logout() throws HttpClientException {

    StringBuilder fullUrl = new StringBuilder(100);
    //      fullUrl.append(HTTP_MYGLOBUL_SITE).append(GLBRequestType.LOGOUT.getPath()).append("?")
    //         .append(GLBRequestType.LOGOUT.getParams());
    fullUrl.append(GLBRequestType.LOGOUT.getPath()).append("?").append(GLBRequestType.LOGOUT.getParams());

    try {//w w w  .  j  ava  2  s . c  o  m
        HttpGet httpGet = new HttpGet(fullUrl.toString());
        HttpResponse resp = httpClient.execute(httpGet, httpContext);
        StatusLine status = resp.getStatusLine();

        if (status.getStatusCode() != HttpStatus.SC_OK)
            throw new HttpClientException(status.getReasonPhrase(), status.getStatusCode());

        resp.getEntity().consumeContent();
    } catch (ClientProtocolException e) {
        throw new HttpClientException("Client protocol error!" + e.getMessage(), e);
    } catch (IOException e) {
        throw new HttpClientException("Client error!" + e.getMessage(), e);
    }
}