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

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

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.estudy.webservice.TestWebservice.java

public static String buildResponse(String url) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    String message;/*from   w w  w .  jav  a2 s  .  c om*/
    httpGet.setHeader("Authorization", "Basic " + "root:gtn");
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        switch (statusCode) {
        case 404:
            //Log.e(Home.class.toString(), "Service not found: " + statusCode);
            message = "Service not found: " + statusCode;
            break;
        case 401:
            // Log.e(Home.class.toString(), "Need to login: " + statusCode);
            message = "Need to login: " + statusCode;
            break;
        case 200:
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            break;
        default:
            //Log.e(Home.class.toString(), "Error : " + statusCode);
            message = "Error: " + statusCode;
            break;
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return builder.toString();
}

From source file:org.zywx.wbpalmstar.platform.push.report.PushReportHttpClient.java

public static boolean isNetWork() {
    HttpGet get = new HttpGet("http://www.baidu.com");
    HttpResponse httpResponse = null;/*from  w  ww .j  a  va  2 s  .c om*/
    HttpClient httpClient = Http.getHttpsClient(60 * 1000);
    get.setHeader("Accept", "*/*");
    try {
        // httpClient = new DefaultHttpClient(setRedirecting());
        httpResponse = httpClient.execute(get);
        int responesCode = httpResponse.getStatusLine().getStatusCode();
        BDebug.d("debug", "responesCode == " + responesCode);
        if (responesCode == 200) {
            // ?
            return true;
        }
    } catch (ClientProtocolException e) {

        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        if (get != null) {
            get.abort();
            get = null;
        }
        if (httpResponse != null) {
            httpResponse = null;
        }
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    return false;
}

From source file:de.fuberlin.agcsw.heraclitus.svont.client.core.ChangeLog.java

public static void updateChangeLog(OntologyStore os, SVoNtProject sp, String user, String pwd) {

    //load the change log from server

    try {//from w  w  w. ja v  a2  s . c o m

        //1. fetch Changelog URI

        URI u = sp.getChangelogURI();

        //2. search for change log owl files
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(
                new AuthScope(u.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_SCHEME),
                new UsernamePasswordCredentials(user, pwd));

        HttpGet httpget = new HttpGet(u);

        System.out.println("executing request" + httpget.getRequestLine());

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(httpget, responseHandler);
        System.out.println(response);
        List<String> files = ChangeLog.extractChangeLogFiles(response);

        ArrayList<ChangeLogElement> changelog = sp.getChangelog();
        changelog.clear();

        //4. sort the revisions

        for (int i = 0; i < files.size(); i++) {
            String fileName = files.get(i);
            System.out.println("rev sort: " + fileName);
            int rev = Integer.parseInt(fileName.split("\\.")[0]);
            changelog.add(new ChangeLogElement(URI.create(u + fileName), rev));
        }

        Collections.sort(changelog, new SortChangeLogsElementsByRev());

        //show sorted changelog

        System.out.print("[");
        for (ChangeLogElement cle : changelog) {
            System.out.print(cle.getRev() + ",");
        }
        System.out.println("]");

        //5. map revision with SVN revisionInformations
        mapRevisionInformation(os, sp, changelog);

        //6. load change log files
        System.out.println("Load Changelog Files");
        for (String s : files) {
            System.out.println(s);
            String req = u + s;
            httpget = new HttpGet(req);
            response = client.execute(httpget, responseHandler);
            //            System.out.println(response);

            // save the changelog File persistent
            IFolder chlFold = sp.getChangeLogFolder();
            IFile chlFile = chlFold.getFile(s);
            if (!chlFile.exists()) {
                chlFile.create(new ByteArrayInputStream(response.getBytes()), true, null);
            }

            os.getOntologyManager().loadOntology(new ReaderInputSource(new StringReader(response)));

        }
        System.out.println("Changelog Ontology successfully loaded");

        //Show loaded onts
        Set<OWLOntology> onts = os.getOntologyManager().getOntologies();
        for (OWLOntology o : onts) {
            System.out.println("loaded ont: " + o.getURI());
        }

        //7 refresh possibly modified Mainontology
        os.getOntologyManager().reloadOntology(os.getMainOntologyLocalURI());

        //8. recalculate Revision Information of the concept of this ontology
        sp.setRevisionMap(createConceptRevisionMap(os, sp));
        sp.saveRevisionMap();

        sp.saveRevisionInformationMap();

        //9. show MetaInfos on ConceptTree

        ConceptTree.refreshConceptTree(os, os.getMainOntologyURI());
        OntologyInformation.refreshOntologyInformation(os, os.getMainOntologyURI());

        //shutdown http connection

        client.getConnectionManager().shutdown();

    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (OWLOntologyCreationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OWLReasonerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SVNException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SVNClientException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.zywx.wbpalmstar.platform.push.report.PushReportHttpClient.java

public static String sendPostWithFile(String url, List<NameValuePair> nameValuePairs,
        Map<String, String> fileMap, Context mCtx) {
    HttpPost post = new HttpPost(url);
    HttpClient httpClient = getSSLHttpClient(mCtx);
    // Post???NameValuePair[]
    // ???request.getParameter("name")
    // List<NameValuePair> params = new ArrayList<NameValuePair>();
    // params.add(new BasicNameValuePair("name", data));
    // post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse httpResponse = null;/*from  w  ww  .j  a  v a  2 s .  co  m*/
    // HttpClient httpClient = null;
    post.setHeader("Accept", "*/*");
    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // // ?HTTP request
        for (int index = 0; index < nameValuePairs.size(); index++) {

            entity.addPart(nameValuePairs.get(index).getName(),
                    new StringBody(nameValuePairs.get(index).getValue(), Charset.forName("UTF-8")));

        }
        if (fileMap != null) {
            Iterator iterator = fileMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = (Entry<String, String>) iterator.next();
                File file = new File(entry.getValue());
                entity.addPart(entry.getKey(), new FileBody(file));
            }
        }

        // post.setEntity(new UrlEncodedFormEntity(nameValuePairs,
        // HTTP.UTF_8));

        post.setEntity(entity);
        // ?HTTP response
        // httpClient = getSSLHttpClient();
        httpResponse = httpClient.execute(post);
        // ??200 ok
        int responesCode = httpResponse.getStatusLine().getStatusCode();
        BDebug.d("debug", "responesCode == " + responesCode);
        if (responesCode == 200) {
            // ?
            return EntityUtils.toString(httpResponse.getEntity());
        }

    } catch (ClientProtocolException e) {

        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        if (post != null) {
            post.abort();
            post = null;
        }
        if (httpResponse != null) {
            httpResponse = null;
        }
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    return null;
}

From source file:org.opensourcetlapp.tl.TLLib.java

public static void logout() throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCookieStore(cookieStore);

    HttpGet httpGet = new HttpGet(LOGOUT_URL + "?t=" + tokenField);

    try {//  ww  w. j a  v  a2 s  .c  om
        httpclient.execute(httpGet);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    }

    loginStatus = false;
    cookieStore = null;
}

From source file:oss.ridendivideapp.PlacesAutoCompleteActivity.java

public static JSONObject getLocationInfo(String address) {
    StringBuilder stringBuilder = new StringBuilder();
    try {//from  ww w.j  ava 2s .com
        /* Code to get top 5 matching addresses to populate autocomplete list
         by parsing through values in a JSON object   */
        address = address.replaceAll(" ", "%20");
        HttpPost httppost = new HttpPost(
                "http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();
        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        Log.e("JSON Object", "JSON Exception", e);
        e.printStackTrace();
    }

    return jsonObject;
}

From source file:com.fatminds.cmis.AlfrescoCmisHelper.java

/**
 * This is here and needed because Alfresco CMIS and Chemistry don't play nice together for relationship deletes
 * as of Alfresco 3.4.2-5 & Chemistry 0.3.0. The problem is that for whatever reason Chemistry strips the "assoc:" prefix
 * off of the relationship ID that ends up on the end of the Delete URL, like this - /alfresco/service/cmis/rel/assoc:363.
 * Left to its own devices, Relationship.delete() will end up issuing a URL like /alfresco/service/cmis/rel/363, and Alfresco
 * will barf. This will hopefully be fixed in Alfesco 4.x.
 * @param proto//from  w w w.  jav  a 2 s  . com
 * @param host
 * @param port
 * @param user
 * @param pass
 * @param assocId
 * @return
 */
public static boolean deleteRelationship(String proto, String host, int port, String user, String pass,
        String assocId) {
    DefaultHttpClient client = new DefaultHttpClient();
    try {
        client.getCredentialsProvider().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, pass));
        HttpDelete delete = new HttpDelete(
                proto + "://" + host + ":" + port + "/alfresco/service/cmis/rel/" + assocId);
        log.info("Sending " + delete.toString());
        HttpResponse resp = client.execute(delete);
        if (resp.getStatusLine().getStatusCode() > 299) { // Alf returns "204 No Content" for success... :-(
            throw new RuntimeException("Get failed (" + resp.getStatusLine().getStatusCode() + ") because "
                    + resp.getStatusLine().getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return true;
}

From source file:org.kde.necessitas.ministro.MinistroActivity.java

public static double downloadVersionXmlFile(Context c, boolean checkOnly) {
    if (!isOnline(c))
        return -1;
    try {//from  w w w .  jav a  2 s. co  m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document dom = null;
        Element root = null;
        URLConnection connection = getVersionUrl(c).openConnection();
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        dom = builder.parse(connection.getInputStream());
        root = dom.getDocumentElement();
        root.normalize();
        double version = Double.valueOf(root.getAttribute("latest"));
        if (MinistroService.instance().getVersion() >= version)
            return MinistroService.instance().getVersion();

        if (checkOnly)
            return version;
        String supportedFeatures = null;
        if (root.hasAttribute("features"))
            supportedFeatures = root.getAttribute("features");
        connection = getLibsXmlUrl(c, version + deviceSupportedFeatures(supportedFeatures)).openConnection();
        File file = new File(MinistroService.instance().getVersionXmlFile());
        file.delete();
        FileOutputStream outstream = new FileOutputStream(MinistroService.instance().getVersionXmlFile());
        InputStream instream = connection.getInputStream();
        byte[] tmp = new byte[2048];
        int downloaded;
        while ((downloaded = instream.read(tmp)) != -1)
            outstream.write(tmp, 0, downloaded);

        outstream.close();
        MinistroService.instance().refreshLibraries(false);
        return version;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:oss.ridendivideapp.TakeRideActivity.java

public static JSONObject getLocationInfo(String address) {
    StringBuilder stringBuilder = new StringBuilder();
    try {//from www .ja  v a  2 s. c o  m

        address = address.replaceAll(" ", "%20");

        HttpPost httppost = new HttpPost(
                "http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();

        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        Log.e("JSON Object", "JSON Exception", e);
    } catch (IOException e) {
        Log.e("JSON Object", "JSON Exception", e);
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        Log.e("JSON Object", "JSON Exception", e);
        e.printStackTrace();
    }

    return jsonObject;
}

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

public static Map<String, String> postData(Context context, String url, Map<String, String> params) {
    // Create a new HttpClient and Post Header
    Map<String, String> response_params = new HashMap<String, String>();
    HttpClient httpclient = getCertifiedHttpClient(context);

    String endpoint = CommonUtilities.SERVER_URL + url;

    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
    String ipSaved = mainPref.getString("ip", "");

    if (ipSaved != null && ipSaved != "") {
        endpoint = CommonUtilities.SERVER_PROTOCOL + ipSaved + ":" + CommonUtilities.SERVER_PORT
                + CommonUtilities.SERVER_APP_ENDPOINT + url;
    }//from www .  j ava  2s.  c o m
    Log.v(TAG, "Posting '" + params.toString() + "' to " + endpoint);
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }

    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] postData = body.getBytes();

    HttpPost httppost = new HttpPost(endpoint);
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    httppost.setHeader("Accept", "*/*");
    httppost.setHeader("User-Agent", "Mozilla/5.0 ( compatible ), Android");

    try {
        // Add your data
        httppost.setEntity(new ByteArrayEntity(postData));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        response_params.put("response", getResponseBody(response));
        response_params.put("status", String.valueOf(response.getStatusLine().getStatusCode()));
        return response_params;
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}