List of usage examples for java.net HttpURLConnection toString
public String toString()
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Checks if is reachable.//from w w w.j a va2s .c o m * * @param uri the uri * @param headers the headers * @return true, if is reachable */ public static boolean isReachable(String uri, HashMap<String, String> headers) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection(); myURLConnection.setRequestMethod("HEAD"); for (String key : headers.keySet()) { myURLConnection.setRequestProperty("Authorization", headers.get(key)); } LOGGER.info(myURLConnection.getResponseCode() + " / " + myURLConnection.toString()); return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:org.comixwall.pffw.GraphsBase.java
/** * Run the controller task./*from w w w .ja v a2 s .c o m*/ * We fetch the graphs using secure http, or fall back to plain http if secure connection fails. * <p> * Note that the PFFW uses a self-signed server certificate. So the code should trust that certificate * and not reject the hostname. * * @return True on success, false on failure. */ @Override public boolean executeTask() { Boolean retval = true; try { String output = controller.execute("symon", "RenderLayout", mLayout, mGraphWidth, mGraphHeight); JSONArray jsonArray = new JSONArray(output); mGraphsJsonObject = new JSONObject(jsonArray.get(0).toString()); Iterator<String> it = mGraphsJsonObject.keys(); while (it.hasNext()) { String title = it.next(); String file = mGraphsJsonObject.getString(title); try { InputStream stream = null; try { String outputGraph = controller.execute("symon", "GetGraph", file); String base64Graph = new JSONArray(outputGraph).get(0).toString(); stream = new ByteArrayInputStream(Base64.decode(base64Graph, Base64.DEFAULT)); } catch (Exception e) { e.printStackTrace(); logger.warning("SSH graph connection exception: " + e.toString()); } // Try secure http if ssh fails if (stream == null) { // 1540861800_404e00f4044d07242a77f802e457f774 String hash = file.substring(file.indexOf('_') + 1); try { // Using https here gives: CertPathValidatorException: Trust anchor for certification path not found. // So we should trust the PFFW server crt and hostname URL secureUrl = new URL("https://" + controller.getHost() + "/symon/graph.php?" + hash); HttpsURLConnection secureUrlConn = (HttpsURLConnection) secureUrl.openConnection(); // Tell the URLConnection to use a SocketFactory from our SSLContext secureUrlConn.setSSLSocketFactory(sslContext.getSocketFactory()); // Install the PFFW host verifier secureUrlConn.setHostnameVerifier(hostnameVerifier); logger.finest("Using secure http: " + secureUrl.toString()); // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts secureUrlConn.setConnectTimeout(5000); secureUrlConn.setReadTimeout(5000); logger.finest("Secure URL connection timeout values: " + secureUrlConn.getConnectTimeout() + ", " + secureUrlConn.getReadTimeout()); stream = secureUrlConn.getInputStream(); } catch (Exception e) { e.printStackTrace(); logger.warning("Secure URL connection exception: " + e.toString()); } // Try plain http if secure http fails if (stream == null) { // ATTENTION: Don't use try-catch here, catch in the outer exception handling URL plainUrl = new URL("http://" + controller.getHost() + "/symon/graph.php?" + hash); HttpURLConnection plainUrlConn = (HttpURLConnection) plainUrl.openConnection(); logger.finest("Using plain http: " + plainUrlConn.toString()); // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts plainUrlConn.setConnectTimeout(5000); plainUrlConn.setReadTimeout(5000); logger.finest("Plain URL connection timeout values: " + plainUrlConn.getConnectTimeout() + ", " + plainUrlConn.getReadTimeout()); stream = plainUrlConn.getInputStream(); } } Bitmap bmp = BitmapFactory.decodeStream(stream); setBitmap(title, bmp); } catch (Exception e) { // We are especially interested in SocketTimeoutException, but catch all e.printStackTrace(); logger.info("GraphsBase doInBackground exception: " + e.toString()); // We should break out of while loop on exception, because all conn attempts have failed break; } } output = controller.execute("pf", "GetReloadRate"); int timeout = Integer.parseInt(new JSONArray(output).get(0).toString()); mRefreshTimeout = timeout < 10 ? 10 : timeout; } catch (Exception e) { e.printStackTrace(); logger.warning("doInBackground exception: " + e.toString()); retval = false; } return retval; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call to the OCC web services * /* w ww. j a v a2s . c o m*/ * @param url * The url * @param isAuthorizedRequest * Whether this request requires the authorization token sending * @param httpMethod * method type (GET, PUT, POST, DELETE) * @param httpBody * Data to be sent in the body (Can be empty) * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws ProtocolException */ public static String getResponse(Context context, String url, Boolean isAuthorizedRequest, String httpMethod, Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException { // Refresh if necessary if (isAuthorizedRequest && WebServiceAuthProvider.tokenExpiredHint(context)) { WebServiceAuthProvider.refreshAccessToken(context); } boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } // Make the connection and get the response OutputStream os; HttpURLConnection connection; if (httpMethod.equals("GET") && httpBody != null && !httpBody.isEmpty()) { url = url + "?" + encodePostBody(httpBody); } URL requestURL = new URL(addParameters(context, url)); if (StringUtils.equalsIgnoreCase(requestURL.getProtocol(), "https")) { trustAllHosts(); HttpsURLConnection https = createSecureConnection(requestURL); https.setHostnameVerifier(DO_NOT_VERIFY); if (isAuthorizedRequest) { String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token"); https.setRequestProperty("Authorization", authValue); } connection = https; } else { connection = createConnection(requestURL); } connection.setRequestMethod(httpMethod); if (!httpMethod.equals("GET") && !httpMethod.equals("DELETE")) { connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); if (httpBody != null && !httpBody.isEmpty()) { os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); } } response = ""; try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (FileNotFoundException e) { LoggingUtils.e(LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), context); response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) // There is an error other than a refresh error, so return the response return response; }
From source file:com.example.appengine.appidentity.UrlShortener.java
/** * Returns a shortened URL by calling the Google URL Shortener API. * * <p>Note: Error handling elided for simplicity. *//* w ww . j ava 2 s. c o m*/ public String createShortUrl(String longUrl) throws Exception { ArrayList<String> scopes = new ArrayList<String>(); scopes.add("https://www.googleapis.com/auth/urlshortener"); final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); // The token asserts the identity reported by appIdentity.getServiceAccountName() JSONObject request = new JSONObject(); request.put("longUrl", longUrl); URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken()); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); request.write(writer); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // Note: Should check the content-encoding. // Any JSON parser can be used; this one is used for illustrative purposes. JSONTokener responseTokens = new JSONTokener(connection.getInputStream()); JSONObject response = new JSONObject(responseTokens); return (String) response.get("id"); } else { try (InputStream s = connection.getErrorStream(); InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) { throw new RuntimeException(String.format("got error (%d) response %s from %s", connection.getResponseCode(), CharStreams.toString(r), connection.toString())); } } }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
public String doRedirect(String urlRedirect) { // android.os.Debug.waitForDebugger(); try {// w ww . ja va 2s .co m Log.d(TAG, "mOcp.m_redirect_uri=" + mOcp.m_redirect_uri); Log.d(TAG, "urlRedirect=" + urlRedirect); // with server phpOIDC, check for '#' if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?")) || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) { Log.d(TAG, "doRedirect : in check"); String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&"); String code = ""; String state = ""; String state_key = "state"; for (int i = 0; i < params.length; i++) { String param = params[i]; int idxEqual = param.indexOf('='); if (idxEqual >= 0) { String key = param.substring(0, idxEqual); String value = param.substring(idxEqual + 1); if (key.startsWith("code")) code = value; if (key.startsWith("state")) state = value; if (key.startsWith("session_state")) { state = value; state_key = "session_state"; } } } // display code and state Logd(TAG, "doRedirect => code: " + code + " / state: " + state); // doRepost(code,state); if (code.length() > 0) { // get token_endpoint endpoint String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url); Log.d(TAG, "token_endpoint=" + token_endpoint); if (isEmpty(token_endpoint)) { Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url); return null; } List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); HttpURLConnection huc = getHUC(token_endpoint); huc.setInstanceFollowRedirects(false); if (mUsePrivateKeyJWT) { nameValuePairs.add(new BasicNameValuePair("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")); String client_assertion = secureProxy.getPrivateKeyJwt(token_endpoint); Logd(TAG, "client_assertion: " + client_assertion); nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion)); } else { huc.setRequestProperty("Authorization", "Basic " + secureProxy.getClientSecretBasic()); } huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); OutputStream os = huc.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8"); BufferedWriter writer = new BufferedWriter(out); nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code")); Logd(TAG, "code: " + code); nameValuePairs.add(new BasicNameValuePair("code", code)); nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri)); Logd(TAG, "redirect_uri" + mOcp.m_redirect_uri); if (state != null && state.length() > 0) nameValuePairs.add(new BasicNameValuePair(state_key, state)); // write URL encoded string from list of key value pairs writer.write(getQuery(nameValuePairs)); writer.flush(); writer.close(); out.close(); os.close(); Logd(TAG, "doRedirect => before connect"); Logd(TAG, "huc=" + huc.toString()); huc.connect(); Logd(TAG, "huc2=" + huc.getContentEncoding()); int responseCode = huc.getResponseCode(); System.out.println("2 - code " + responseCode); Log.d(TAG, "doRedirect => responseCode " + responseCode); InputStream in = null; try { in = new BufferedInputStream(huc.getInputStream()); } catch (IOException ioe) { sysout("io exception: " + huc.getErrorStream()); } if (in != null) { String result = convertStreamToString(in); // now you have the string representation of the HTML request in.close(); Logd(TAG, "doRedirect: " + result); // save as static for now return result; } else { Logd(TAG, "doRedirect null"); } } } } catch (Exception e) { e.printStackTrace(); } return null; }