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:com.meltmedia.cadmium.blackbox.test.CadmiumAssertions.java

/**
 * <p>Asserts that a remote resource exists.</p>
 * @param message The message that will be in the error if the remote resource doesn't exist.
 * @param remoteLocation A string containing the URL location of the remote resource to check.
 * @param username The Basic HTTP auth username.
 * @param password The Basic HTTP auth password.
 * @return The content of the remote file.
 *//*from  w ww . j av  a 2  s. co m*/
public static HttpEntity assertExistsRemotely(String message, String remoteLocation, String username,
        String password) {
    DefaultHttpClient client = new DefaultHttpClient();
    try {
        HttpGet get = new HttpGet(remoteLocation);
        if (!StringUtils.isEmptyOrNull(username) && !StringUtils.isEmptyOrNull(password)) {
            get.setHeader("Authorization", encodeForBasicAuth(username, password));
        }

        HttpResponse resp = client.execute(get);
        if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new AssertionFailedError(message);
        }
        return resp.getEntity();
    } catch (ClientProtocolException e) {
        throw new AssertionFailedError(e.getMessage() + ": " + message);
    } catch (IOException e) {
        throw new AssertionFailedError(e.getMessage() + ": " + message);
    }
}

From source file:se.vgregion.util.HTTPUtils.java

public static HttpResponse basicAuthRequest(String url, String username, String password,
        DefaultHttpClient client) throws HttpUtilsException {
    HttpGet get = new HttpGet(url);

    client.getCredentialsProvider().setCredentials(new AuthScope(null, 443),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);
    HttpResponse response;//from   w  w w.  ja va2 s.c  o m
    try {
        response = client.execute(get, localcontext);
    } catch (ClientProtocolException e) {
        throw new HttpUtilsException("Invalid http protocol", e);
    } catch (IOException e) {
        throw new HttpUtilsException(e.getMessage(), e);
    }
    return response;
}

From source file:com.oneteam.framework.android.location.direction.GDirectionsApiUtils.java

/**
 * Simple Rest Call to the Google Direction WebService
 * http://maps.googleapis.com/maps/api/directions/json?
 * //  www  .j  a va  2s  .c o m
 * @param start
 *            Starting Point
 * @param end
 *            Ending Point
 * @param mode
 *            The mode (walking,driving..)
 * @return The json returned by the webServer
 */
private static String getJSONDirection(LatLng start, LatLng end, String mode) {
    String url = "http://maps.googleapis.com/maps/api/directions/json?" + "origin=" + start.latitude + ","
            + start.longitude + "&destination=" + end.latitude + "," + end.longitude
            + "&sensor=false&units=metric&mode=" + mode;
    String responseBody = null;
    // The HTTP get method send to the URL
    HttpGet getMethod = new HttpGet(url);
    // The basic response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    // instantiate the http communication
    HttpClient client = new DefaultHttpClient();
    // Call the URL and get the response body
    try {
        responseBody = client.execute(getMethod, responseHandler);
    } catch (ClientProtocolException e) {
        Log.e(tag, e.getMessage());
    } catch (IOException e) {
        Log.e(tag, e.getMessage());
    }
    Log.e(tag, responseBody);
    // parse the response body
    return responseBody;
}

From source file:com.speakingcode.freemusicarchive.api.FMAConnector.java

/**
 * Makes the HTTP GET request to the provided REST url 
 * @param requestUrl the URL to request/*from   w w  w  .  j  a  v a2  s.c om*/
 * @return The string of the response from the HTTP request
 */
public static String callWebService(String requestUrl) {
    String deviceId = "xxxxx";

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(requestUrl);
    request.addHeader("deviceId", deviceId);

    ResponseHandler<String> handler = new BasicResponseHandler();
    String result = "";

    try {
        result = httpclient.execute(request, handler);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Log.e(TAG, "ClientProtocolException in callWebService(). " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(TAG, "IOException in callWebService(). " + e.getMessage());
    }

    httpclient.getConnectionManager().shutdown();
    Log.i(TAG, "**callWebService() successful. Result: **");
    Log.i(TAG, result);
    Log.i(TAG, "*****************************************");

    return result;
}

From source file:DeliverWork.java

private static String saveIntoWeed(RemoteFile remoteFile, String projectId)
        throws SQLException, UnsupportedEncodingException {
    String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id="
            + URLEncoder.encode(remoteFile.getFileId(), "utf-8");
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String res = "";
    try {//from w w w.  j a  v  a  2  s. c  o m
        httpClient = HttpClients.createSystem();
        // http(get?)
        HttpGet httpget = new HttpGet(url);
        response = httpClient.execute(httpget);
        HttpEntity result = response.getEntity();
        String fileName = remoteFile.getFileName();
        FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName,
                new ByteArrayInputStream(EntityUtils.toByteArray(result)));
        System.out.println(fileHandleStatus);
        File file = new File();
        if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) {
            file.setContentType(result.getContentType().getValue());
        } else {
            file.setContentType("application/error");
        }
        file.setDataId(Integer.parseInt(projectId));
        file.setName(fileName);
        if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg")
                || fileName.contains(".png") || fileName.contains(".gif")) {
            file.setType(1);
        } else if (fileName.contains(".doc") || fileName.contains(".docx")) {
            file.setType(2);
        } else if (fileName.contains(".xlsx") || fileName.contains("xls")) {
            file.setType(3);
        } else if (fileName.contains(".pdf")) {
            file.setType(4);
        } else {
            file.setType(5);
        }
        String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName);
        file.setUrl(accessUrl);
        file.setSize(fileHandleStatus.getSize());
        file.setPostTime(new java.util.Date());
        file.setStatus(0);
        file.setEnumValue(findFileType(remoteFile.getFileType()));
        file.setResources(1);
        //            JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver");
        //            Connection connection = jdbcFactoryChanye.getConnection();
        DatabaseMetaData dmd = connection.getMetaData();
        PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" });
        ps.setString(1, sdf.format(file.getPostTime()));
        ps.setInt(2, file.getType());
        ps.setString(3, file.getEnumValue());
        ps.setInt(4, file.getDataId());
        ps.setString(5, file.getUrl());
        ps.setString(6, file.getName());
        ps.setString(7, file.getContentType());
        ps.setLong(8, file.getSize());
        ps.setInt(9, file.getStatus());
        ps.setInt(10, file.getResources());
        ps.executeUpdate();
        if (dmd.supportsGetGeneratedKeys()) {
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()) {
                System.out.println(rs.getLong(1));
            }
        }
        ps.close();
        res = "success";
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return res;
}

From source file:com.mingsoft.util.proxy.Proxy.java

/**
 * get/*from w w  w .  ja v a 2  s.  c o  m*/
 * 
 * @param url
 *            ?<br>
 * @param header
 *            ?Header new Header()<br>
 * @param params
 *            ?<br>
 * @return Result 
 */
public static Result get(String url, com.mingsoft.util.proxy.Header header, Map params) {
    //log.info("?" + url);
    // Httpclient
    DefaultHttpClient client = new DefaultHttpClient();
    // ??
    url = url + (null == params ? "" : assemblyParameter(params));
    // get
    HttpGet httpGet = new HttpGet(url);
    // cookie?()
    httpGet.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    // ?
    if (null != header && header.getHeaders().size() > 0) {
        httpGet.setHeaders(Proxy.assemblyHeader(header.getHeaders()));
    }
    // ?HttpResponse
    HttpResponse response;
    try {
        response = client.execute(httpGet);
        // 
        // httpGet.abort();
        // HttpEntity
        HttpEntity entity = response.getEntity();
        // ??
        Result result = new Result();
        // cookie
        result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
        // ?
        result.setStatusCode(response.getStatusLine().getStatusCode());
        // 
        result.setHeaders(response.getAllHeaders());
        // ?
        result.setHttpEntity(entity);
        return result;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    }
    return null;
}

From source file:com.mingsoft.util.proxy.Proxy.java

/**
 * get??/*  ww  w .  j  a  v  a  2s .  co m*/
 * 
 * @param url
 *            ?<br>
 * @param fileUrl
 *            ????<br>
 * @param header
 *            ?Header new Header()<br>
 */
public static void getRandCode(String url, com.mingsoft.util.proxy.Header header, String fileUrl) {
    DefaultHttpClient client = new DefaultHttpClient();

    //log.info("?" + url);
    // get
    HttpGet get = new HttpGet(url);
    // cookie?()
    get.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    Map _headers = header.getHeaders();
    // ?
    if (null != header && _headers.size() > 0) {
        get.setHeaders(Proxy.assemblyHeader(_headers));
    }
    HttpResponse response;
    try {
        response = client.execute(get);

        // ?
        // Header[] h = (Header[]) response.getAllHeaders();
        // for (int i = 0; i < h.length; i++) {
        // Header a = h[i];
        // }

        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        // cookie???cookie
        header.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
        int temp = 0;
        // 
        File file = new File(fileUrl);
        // ??
        FileOutputStream out = new FileOutputStream(file);
        while ((temp = in.read()) != -1) {
            out.write(temp);
        }
        in.close();
        out.close();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    }
}

From source file:st.brothas.mtgoxwidget.MtGoxWidgetProvider.java

private static JSONObject getLatestQuoteJSON(WidgetPreferences preferences) {
    HttpGet httpget = new HttpGet(
            preferences.getRateService().getTickerUrl(preferences.getCurrencyConversion()));
    HttpResponse response;/*  w ww  .j ava 2 s .  co  m*/
    try {
        response = HttpManager.execute(httpget);
        HttpEntity entity = response.getEntity();
        JSONObject jObject = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = convertStreamToString(instream);
            //                    Log.d(LOG_TAG, "Getting URI: " + httpget.getURI());
            //                    Log.d(LOG_TAG, "Response: " + result);
            jObject = new JSONObject(result);
            instream.close();
        }
        return jObject;
    } catch (ClientProtocolException e) {
        Log.e(LOG_TAG, "Error when getting JSON", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error when getting JSON: " + e.getMessage());
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Error when parsing JSON", e);
    }
    return null;
}

From source file:org.openbitcoinwidget.WidgetProvider.java

private static String getLatestQuote(WidgetPreferences preferences) {
    HttpGet httpget = new HttpGet(
            preferences.getRateService().getTickerUrl(preferences.getCurrencyConversion()));
    HttpResponse response;/*  www . j a  v  a2  s  .  co  m*/
    try {
        response = HttpManager.execute(httpget);
        HttpEntity entity = response.getEntity();
        String responseString = "";
        if (entity != null) {
            InputStream inStream = entity.getContent();
            responseString = convertStreamToString(inStream);
            inStream.close();
        }
        return responseString;
    } catch (ClientProtocolException e) {
        Log.e(LOG_TAG, "Error when getting JSON", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error when getting JSON: " + e.getMessage());
    }
    return null;
}

From source file:org.apache.ofbiz.passport.user.GitHubAuthenticator.java

public static Map<String, Object> getUserInfo(HttpGet httpGet, String accessToken, String tokenType,
        Locale locale) throws AuthenticatorException {
    JSON userInfo = null;//ww w  .  j  ava2s  .  c om
    httpGet.setConfig(PassportUtil.StandardRequestConfig);
    CloseableHttpClient jsonClient = HttpClients.custom().build();
    httpGet.setHeader(PassportUtil.AUTHORIZATION_HEADER, tokenType + " " + accessToken);
    httpGet.setHeader(PassportUtil.ACCEPT_HEADER, "application/json");
    CloseableHttpResponse getResponse = null;
    try {
        getResponse = jsonClient.execute(httpGet);
        String responseString = new BasicResponseHandler().handleResponse(getResponse);
        if (getResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Debug.logInfo("Json Response from GitHub: " + responseString, module);
            userInfo = JSON.from(responseString);
        } else {
            String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError",
                    UtilMisc.toMap("error", responseString), locale);
            throw new AuthenticatorException(errMsg);
        }
    } catch (ClientProtocolException e) {
        throw new AuthenticatorException(e.getMessage());
    } catch (IOException e) {
        throw new AuthenticatorException(e.getMessage());
    } finally {
        if (getResponse != null) {
            try {
                getResponse.close();
            } catch (IOException e) {
                // do nothing
            }
        }
    }
    JSONToMap jsonMap = new JSONToMap();
    Map<String, Object> userMap;
    try {
        userMap = jsonMap.convert(userInfo);
    } catch (ConversionException e) {
        throw new AuthenticatorException(e.getMessage());
    }
    return userMap;
}