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.ubicompforall.BusTUC.Queries.Browser.java

public String getRequestServer2(String stop, Boolean formated, double lat, double lon, int numStops, int dist,
        Context context) {/*from  w  w  w  .  jav  a  2s  . c  om*/
    String html_string = null;
    HttpGet m_get = new HttpGet();
    try {
        stop = URLEncoder.encode(stop, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    // HttpPost m_post= new
    // HttpPost("http://m.atb.no/xmlhttprequest.php?service=routeplannerOracle.getOracleAnswer&question=");
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String t_id = tm.getDeviceId();
        String tmp = "TABuss";
        String p_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
        m_get.setURI(new URI("http://busstjener.idi.ntnu.no/MultiBRISserver/MBServlet?dest=" + stop + "&lat="
                + lat + "&long=" + lon + "&type=json&nStops=" + numStops + "&maxWalkDist=" + dist + "&key="
                + tmp + p_id));
        HttpResponse m_response = m_client.execute(m_get);
        // Request
        html_string = httpF.requestServer(m_response);
        // Will fail if server is busy or down
        Log.v("html_string", "Returned html: " + html_string);
        // Long newTime = System.nanoTime() - time;
        // System.out.println("TIMEEEEEEEEEEEEEEEEEEEEE: " +
        // newTime/1000000000.0);
    } catch (ClientProtocolException e) {
        Log.v("CLIENTPROTOCOL EX", "e:" + e.toString());
    } catch (IOException e) {
        Log.v("IO EX", "e:" + e.toString());

    } catch (NullPointerException e) {
        Log.v("NULL", "NullPointer");
    } catch (StringIndexOutOfBoundsException e) {
        Log.v("StringIndexOutOfBounds", "Exception");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return html_string;
}

From source file:org.cloudsimulator.controller.ServiceMetricController.java

public void sendXmlRdfOfServiceMetricToKB() {
    ResponseMessageString responseMessage;
    hideSendForm();//from   www  .  ja v  a 2 s  .co  m
    try {
        responseMessage = KBDAO.sendXMLToKB("POST", this.ipOfKB, "serviceMetric", "",
                this.createdXmlRdfServiceMetric);

        if (responseMessage != null) {
            if (responseMessage.getResponseCode() < 400) {
                this.sendDone = "done";
            } else {
                this.sendDone = "error";
            }

            if (responseMessage.getResponseBody() != null) {
                this.alertMessage = "<strong>Response Code </strong>: " + responseMessage.getResponseCode()
                        + " <strong>Reason</strong>: " + responseMessage.getReason() + "<br />"
                        + responseMessage.getResponseBody().replace("\n", "<br />");
            } else {
                this.alertMessage = "<strong>Response Code </strong>: " + responseMessage.getResponseCode()
                        + " <strong>Reason</strong>: " + responseMessage.getReason() + "<br />";
            }
        }

    } catch (ClientProtocolException e) {
        LOGGER.error(e.getMessage(), e);
        this.sendDone = "exception";
        this.alertMessage = e.toString();
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        this.sendDone = "exception";
        this.alertMessage = e.toString();
    }
}

From source file:org.ptlug.ptwifiauth.UserSession.java

private boolean createUser(String csrf_token, String username_lower, String email) {
    try {/*from   w  w w . jav  a  2 s  .co m*/

        httppost = new HttpPost(AppConsts.base_url);

        httppost.setEntity(new UrlEncodedFormEntity(PostParametersBuilder
                .buildCreateUserParameters(this.username, this.password, csrf_token, username_lower, email)));

        httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        last_response = httpclient.execute(httppost);

        this.debugCookies();

        Logger.getInstance().doLog(LogConsts.html_acquired, getHtmlContent());

        httppost = new HttpPost(GlobalSpace.login_url);

        return true;

    }

    catch (ClientProtocolException e) {
        Log.i(LogConsts.login_result, "ClientProtocolException " + e.toString());
        return false;
    }

    catch (IOException e) {
        Log.i(LogConsts.login_result, "IOException " + e.toString());
        return false;
    }
}

From source file:nextflow.fs.dx.api.DxHttpClient.java

/**
 * Issues a request against the specified resource and returns either the
 * text of the response or the parsed JSON of the response (depending on
 * whether parseResponse is set).//from  ww  w .  j ava  2s .co  m
 */
private ParsedResponse requestImpl(String resource, String data, boolean parseResponse) throws IOException {
    HttpPost request = new HttpPost(apiserver + resource);

    request.setHeader("Content-Type", "application/json");
    request.setHeader("Authorization", securityContext.get("auth_token_type").textValue() + " "
            + securityContext.get("auth_token").textValue());
    request.setEntity(new StringEntity(data));

    // Retry with exponential backoff
    int timeout = 1;

    for (int i = 0; i <= NUM_RETRIES; i++) {
        HttpResponse response = null;
        boolean okToRetry = false;

        try {
            response = httpclient.execute(request);
        } catch (ClientProtocolException e) {
            log.error(errorMessage("POST", resource, e.toString(), timeout, i + 1, NUM_RETRIES));
        } catch (IOException e) {
            log.error(errorMessage("POST", resource, e.toString(), timeout, i + 1, NUM_RETRIES));
        }

        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();

            HttpEntity entity = response.getEntity();

            if (statusCode == HttpStatus.SC_OK) {
                // 200 OK

                byte[] value = EntityUtils.toByteArray(entity);
                int realLength = value.length;
                if (entity.getContentLength() >= 0 && realLength != entity.getContentLength()) {
                    String errorStr = "Received response of " + realLength + " bytes but Content-Length was "
                            + entity.getContentLength();
                    log.error(errorMessage("POST", resource, errorStr, timeout, i + 1, NUM_RETRIES));
                } else {
                    if (parseResponse) {
                        JsonNode responseJson = null;
                        try {
                            responseJson = DxJson.parseJson(new String(value, "UTF-8"));
                        } catch (JsonProcessingException e) {
                            if (entity.getContentLength() < 0) {
                                // content-length was not provided, and the
                                // JSON could not be parsed. Retry since
                                // this is a streaming request from the
                                // server that probably just encountered a
                                // transient error.
                            } else {
                                throw e;
                            }
                        }
                        if (responseJson != null) {
                            return new ParsedResponse(null, responseJson);
                        }
                    } else {
                        return new ParsedResponse(new String(value, "UTF-8"), null);
                    }
                }
            } else {
                // Non-200 status codes.

                // 500 InternalError should get retried. 4xx errors should
                // be considered not recoverable.
                if (statusCode < 500) {
                    throw new IOException(EntityUtils.toString(entity));
                } else {
                    log.error(errorMessage("POST", resource, EntityUtils.toString(entity), timeout, i + 1,
                            NUM_RETRIES));
                }
            }
        }

        if (i < NUM_RETRIES) {
            try {
                Thread.sleep(timeout * 1000);
            } catch (InterruptedException e) {
                log.debug("Stopped sleep caused by: {}", e.getMessage());
            }
            timeout *= 2;
        }
    }

    throw new IOException("POST " + resource + " failed");
}

From source file:org.ptlug.ptwifiauth.UserSession.java

public boolean login() {
    try {//from  w  w  w .  j  a  va 2  s.c  om
        int status_def = this.getDefaultUrl();

        if (status_def != 1 && status_def != 4)
            return false;

        httppost.setEntity(new UrlEncodedFormEntity(
                PostParametersBuilder.buildLoginParameters(this.username, this.password)));

        Logger.getInstance().doLog("UserNamePassword", this.username + this.password);

        httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        last_response = httpclient.execute(httppost);

        this.debugCookies();

        return verifyLogin();

    }

    catch (ClientProtocolException e) {
        Logger.getInstance().doLog(LogConsts.login_result, "ClientProtocolException " + e.toString());
        return false;
    }

    catch (IOException e) {
        Logger.getInstance().doLog(LogConsts.login_result, "IOException " + e.getMessage());
        return false;
    }

}

From source file:org.ptlug.ptwifiauth.UserSession.java

private String getToken() {
    try {//  ww  w.  j a va2  s . co  m

        httppost.setEntity(new UrlEncodedFormEntity(PostParametersBuilder.buildTokenRequestParameters()));

        httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        last_response = httpclient.execute(httppost);

        this.debugCookies();

        String html = getHtmlContent();

        int token_id = html.indexOf("ap_user[_csrf_token]");

        int start_parse_pos = 29;

        String token = html.substring(token_id + start_parse_pos,
                token_id + start_parse_pos + AppConsts.cdrf_token_len);

        Logger.getInstance().doLog(LogConsts.token_acquired, "" + token);

        return token;

    }

    catch (ClientProtocolException e) {
        Logger.getInstance().doLog(LogConsts.login_result, "ClientProtocolException " + e.toString());
        return null;
    }

    catch (IOException e) {
        Logger.getInstance().doLog(LogConsts.login_result, "IOException " + e.toString());
        return null;
    }

}

From source file:org.ptlug.ptwifiauth.UserSession.java

public int getDefaultUrl() {
    try {//from  w  w  w.jav  a 2s  .  c om

        httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        httpget.getParams().setParameter("http.protocol.handle-redirects", false);
        last_response = httpclient.execute(httpget);

        this.debugCookies();

        String html = getHtmlContent();

        Logger.getInstance().doLog("HTMLLOGIN", html);

        if (html.contains("The document has moved")) {
            return 4;
        }

        if (html.contains("<h2>Please")) {
            int token_id = html.indexOf("<h2>Please");

            String addr = html.substring(token_id, html.length());

            GlobalSpace.login_url = addr.split("'")[1];

            Logger.getInstance().doLog("HTMLREDIRECT", "" + addr.split("'")[1]);

            httppost = new HttpPost(GlobalSpace.login_url);

            return 1;
        }

        // else
        // AppConsts.login_url = "http://wifi.ptlug.org/login";

        return 0; // SET 1 ONLY FOR TESTING!!!

    }

    catch (ClientProtocolException e) {
        Logger.getInstance().doLog(LogConsts.login_result, "ClientProtocolException " + e.toString());
        return 2;
    }

    catch (IOException e) {
        Logger.getInstance().doLog(LogConsts.login_result, "IOException " + e.toString());
        return 2;
    }
}

From source file:biz.mosil.webtools.MosilWeb.java

/**
 *  Get ?//w w w. j  a  v  a2s .c  o  m
 * */
public MosilWeb actGet(final String _queryString) {
    chkHostName();

    String targetUrl = "http://" + mHostName;
    if (!_queryString.equals("")) {
        targetUrl += "?" + _queryString;
    }

    HttpGet httpGet = new HttpGet(targetUrl);
    DefaultHttpClient httpClient = new DefaultHttpClient(mHttpParams);

    try {
        mHttpResponse = httpClient.execute(httpGet);
        if (mHttpResponse != null) {
            mResponse = EntityUtils.toString(mHttpResponse.getEntity());
        }
    } catch (ClientProtocolException _ex) {
        Log.e(TAG, "Client Protocol Exception: " + _ex.toString());
    } catch (IOException _ex) {
        Log.e(TAG, "IO Exception: " + _ex.toString());
    }

    return this;
}

From source file:com.nubits.nubot.RPC.NuRPCClient.java

private JSONObject invokeRPC(String id, String method, List params) {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    JSONObject json = new JSONObject();
    json.put("id", id);
    json.put("method", method);
    if (null != params) {
        JSONArray array = new JSONArray();
        array.addAll(params);/*w ww  .j av a 2s.com*/
        json.put("params", params);
    }
    JSONObject responseJsonObj = null;
    try {
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(this.ip, this.port),
                new UsernamePasswordCredentials(this.rpcUsername, this.rpcPassword));
        StringEntity myEntity = new StringEntity(json.toJSONString());
        if (Global.options.verbose) {
            LOG.info("RPC : " + json.toString());
        }
        HttpPost httppost = new HttpPost("http://" + this.ip + ":" + this.port);
        httppost.setEntity(myEntity);

        if (Global.options.verbose) {
            LOG.info("RPC executing request :" + httppost.getRequestLine());
        }
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        if (Global.options.verbose) {
            LOG.info("RPC----------------------------------------");
            LOG.info("" + response.getStatusLine());

            if (entity != null) {
                LOG.info("RPC : Response content length: " + entity.getContentLength());
            }
        }
        JSONParser parser = new JSONParser();
        String entityString = EntityUtils.toString(entity);
        LOG.debug("Entity = " + entityString);
        /* TODO In case of wrong username/pass the response would be the following .Consider parsing it.
        Entity = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
                <HTML>
                <HEAD>
                <TITLE>Error</TITLE>
                <META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>
                </HEAD>
                <BODY><H1>401 Unauthorized.</H1></BODY>
                </HTML>
         */
        responseJsonObj = (JSONObject) parser.parse(entityString);
    } catch (ClientProtocolException e) {
        LOG.error("Nud RPC Connection problem:" + e.toString());
        this.connected = false;
    } catch (IOException e) {
        LOG.error("Nud RPC Connection problem:" + e.toString());
        this.connected = false;
    } catch (ParseException ex) {
        LOG.error("Nud RPC Connection problem:" + ex.toString());
        this.connected = false;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return responseJsonObj;
}

From source file:zumzum.app.zunzuneando.visor.weather.YahooWeather.java

private String getWeatherString(Context context, String woeidNumber) {
    MyLog.d("query yahoo weather with WOEID number : " + woeidNumber);

    String qResult = "";
    String queryString = "http://weather.yahooapis.com/forecastrss?w=" + woeidNumber + "&u=c";

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(queryString);

    try {/*from  w  w  w. j a  v  a2  s  .c o  m*/
        HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

        if (httpEntity != null) {
            InputStream inputStream = httpEntity.getContent();
            Reader in = new InputStreamReader(inputStream);
            BufferedReader bufferedreader = new BufferedReader(in);
            StringBuilder stringBuilder = new StringBuilder();

            String readLine = null;

            while ((readLine = bufferedreader.readLine()) != null) {
                MyLog.d(readLine);
                stringBuilder.append(readLine + "\n");
            }

            qResult = stringBuilder.toString();
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
    }

    return qResult;
}