List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.none.tom.simplerssreader.net.FeedDownloader.java
@SuppressWarnings("ConstantConditions") public static InputStream getInputStream(final Context context, final String feedUrl) { final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class); final NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null || !info.isConnected()) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK); LogUtils.logError("No network connection"); return null; }// w w w .j ava 2s.c o m URL url; try { url = new URL(feedUrl); } catch (final MalformedURLException e) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e); return null; } final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context); final boolean useHttpTorProxy = networkPrefs[0]; final boolean httpsOnly = networkPrefs[1]; final boolean followRedir = networkPrefs[2]; for (int nrRedirects = 0;; nrRedirects++) { if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS); LogUtils.logError("Too many redirects"); return null; } HttpURLConnection conn = null; try { if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY); LogUtils.logError("Attempting insecure connection"); return null; } if (useHttpTorProxy) { conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT))); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name()); conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.connect(); final int responseCode = conn.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_OK: return getInputStream(conn.getInputStream()); case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: if (followRedir) { final String location = conn.getHeaderField("Location"); url = new URL(url, location); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) { SharedPrefUtils.updateSubscriptionUrl(context, url.toString()); } continue; } ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED); LogUtils.logError("Couldn't follow redirect"); return null; default: if (responseCode < 0) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE); LogUtils.logError("No valid HTTP response"); return null; } else if (responseCode >= 400 && responseCode <= 500) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT); } else if (responseCode >= 500 && responseCode <= 600) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED); } LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage()); return null; } } catch (final IOException e) { if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable")) || e instanceof SocketTimeoutException || e instanceof UnknownHostException) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e); } return null; } finally { if (conn != null) { conn.disconnect(); } } } }
From source file:bluevia.InitService.java
boolean subscribeNotifications() { boolean result = true; String[] countryShortNumbers = { MO_UK, MO_SP, MO_GE, MO_BR, MO_MX, MO_AR, MO_CH, MO_CO }; int i = 0;//from w w w . j a va2 s .com for (i = 0; i < countryShortNumbers.length; i++) { try { OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(Util.BlueViaOAuth.consumer_key, Util.BlueViaOAuth.consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); URL apiURI = new URL( "https://api.bluevia.com/services/REST/SMS/inbound/subscriptions?version=v1&alt=json"); HttpURLConnection request = (HttpURLConnection) apiURI.openConnection(); Random rand = new Random(); Date now = new Date(); rand.setSeed(now.getTime()); Long correlator = rand.nextLong(); if (correlator < 0) correlator = -1 * correlator; String jsonSubscriptionMsg = "{\"smsNotification\":{\"reference\":{\"correlator\": \"%s\",\"endpoint\": \"%s\"},\"destinationAddress\":{\"phoneNumber\":\"%s\"},\"criteria\":\"%s\"}}"; String szBody = String.format(jsonSubscriptionMsg, "bv" + correlator.toString().substring(0, 16), Util.getCallbackDomain() + "/notifySmsReception", countryShortNumbers[i], Util.BlueViaOAuth.app_keyword); request.setRequestProperty("Content-Type", "application/json"); request.setRequestProperty("Content-Length", "" + Integer.toString(szBody.getBytes().length)); request.setRequestMethod("POST"); request.setDoOutput(true); consumer.sign(request); request.connect(); OutputStream os = request.getOutputStream(); os.write(szBody.getBytes()); os.flush(); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_CREATED) Util.addUnsubscriptionURI(countryShortNumbers[i], request.getHeaderField("Location"), "bv" + correlator.toString().substring(0, 16)); else { logger.severe(String.format("Error %d registering Notification URLs:%s", rc, request.getResponseMessage())); } } catch (Exception e) { logger.severe("Exception raised: %s" + e.getMessage()); } } return result; }
From source file:org.apache.hadoop.chukwa.datatrigger.HttpTriggerAction.java
private void makeHttpRequest(URL url, String method, Map<String, String> headers, String body, int connectTimeout, int readTimeout) throws IOException { if (url == null) { return;//ww w . ja v a2 s . co m } // initialize the connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); // set headers boolean contentLengthExists = false; if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); if (log.isDebugEnabled()) { log.debug("Setting header " + name + ": " + value); } if (name.equalsIgnoreCase("content-length")) { contentLengthExists = true; } conn.setRequestProperty(name, value); } } // set content-length if not already set if (!"GET".equals(method) && !contentLengthExists) { String contentLength = body != null ? String.valueOf(body.length()) : "0"; conn.setRequestProperty("Content-Length", contentLength); } // send body if it exists if (body != null) { conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8")); writer.write(body); writer.flush(); writer.close(); } else { conn.setDoOutput(false); } // read reponse code/message and dump response log.info("Making HTTP " + method + " to: " + url); int responseCode = conn.getResponseCode(); log.info("HTTP Response code: " + responseCode); if (responseCode != 200) { log.info("HTTP Response message: " + conn.getResponseMessage()); } else { BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\n"); } sb.append(line); } log.info("HTTP Response:\n" + sb); reader.close(); } conn.disconnect(); }
From source file:com.hortonworks.historian.nifi.reporter.HistorianDeanReporter.java
private JSONArray postJSONArrayToUrl(String urlString, String[] basicAuth, String payload) throws IOException, JSONException { String userPassString = basicAuth[0] + ":" + basicAuth[1]; JSONArray jsonArray = null;// w w w . ja v a 2s. co m try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Authorization", "Basic " + new String(Base64.encode(userPassString.getBytes()))); connection.setRequestProperty("Content-Type", "application/json"); OutputStream os = connection.getOutputStream(); os.write(payload.getBytes()); os.flush(); if (connection.getResponseCode() > 202) { throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode() + " : " + connection.getResponseMessage()); } InputStream content = (InputStream) connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(content, Charset.forName("UTF-8"))); String jsonText = readAll(rd); jsonArray = new JSONArray(jsonText); } catch (Exception e) { e.printStackTrace(); } return jsonArray; }
From source file:org.elasticsearch.metrics.ElasticsearchReporter.java
/** * This index template is automatically applied to all indices which start with the index name * The index template simply configures the name not to be analyzed *///from ww w. j a v a2 s .c om private void checkForIndexTemplate() { try { HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD"); if (connection == null) { LOGGER.error("Could not connect to any configured elasticsearch instances: {}", Arrays.asList(hosts)); return; } connection.disconnect(); boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND; // nothing there, lets create it if (isTemplateMissing) { LOGGER.debug("No metrics template found in elasticsearch. Adding..."); HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT"); if (putTemplateConnection == null) { LOGGER.error("Error adding metrics template to elasticsearch"); return; } JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream()); json.writeStartObject(); json.writeStringField("template", index + "*"); json.writeObjectFieldStart("mappings"); json.writeObjectFieldStart("_default_"); json.writeObjectFieldStart("_all"); json.writeBooleanField("enabled", false); json.writeEndObject(); json.writeObjectFieldStart("properties"); json.writeObjectFieldStart("name"); json.writeObjectField("type", "string"); json.writeObjectField("index", "not_analyzed"); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.flush(); putTemplateConnection.disconnect(); if (putTemplateConnection.getResponseCode() != 200) { LOGGER.error( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage()); } } checkedForIndexTemplate = true; } catch (IOException e) { LOGGER.error("Error when checking/adding metrics template to elasticsearch", e); } }
From source file:net.myrrix.client.ClientRecommender.java
/** * @param userID user for which recommendations are to be computed * @param howMany desired number of recommendations * @param considerKnownItems if true, items that the user is already associated to are candidates * for recommendation. Normally this is {@code false}. * @param rescorerParams optional parameters to send to the server's {@code RescorerProvider} * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least * @throws NoSuchUserException if the user is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs * @throws UnsupportedOperationException if rescorer is not null *//*from w ww . ja v a2s. c om*/ public List<RecommendedItem> recommend(long userID, int howMany, boolean considerKnownItems, String[] rescorerParams) throws TasteException { StringBuilder urlPath = new StringBuilder(); urlPath.append("/recommend/"); urlPath.append(userID); appendCommonQueryParams(howMany, considerKnownItems, rescorerParams, urlPath); TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(userID)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchUserException(userID); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:com.irccloud.android.GingerbreadImageProxy.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;/*w w w . j a va 2 s .co m*/ } URL url = new URL(request.getRequestLine().getUri()); HttpURLConnection conn = null; Proxy proxy = null; String host = null; int port = -1; if (Build.VERSION.SDK_INT < 11) { Context ctx = IRCCloudApplication.getInstance().getApplicationContext(); if (ctx != null) { host = android.net.Proxy.getHost(ctx); port = android.net.Proxy.getPort(ctx); } } else { host = System.getProperty("http.proxyHost", null); try { port = Integer.parseInt(System.getProperty("http.proxyPort", "8080")); } catch (NumberFormatException e) { port = -1; } } if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("127.0.0.1") && port > 0) { InetSocketAddress proxyAddr = new InetSocketAddress(host, port); proxy = new Proxy(Proxy.Type.HTTP, proxyAddr); } if (url.getProtocol().toLowerCase().equals("https")) { conn = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY)); } else { conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY)); } conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setUseCaches(true); if (!isRunning) return; try { client.getOutputStream().write( ("HTTP/1.0 " + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n").getBytes()); if (conn.getResponseCode() == 200 && conn.getInputStream() != null) { byte[] buff = new byte[8192]; int readBytes; while (isRunning && (readBytes = conn.getInputStream().read(buff, 0, buff.length)) != -1) { client.getOutputStream().write(buff, 0, readBytes); } } } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } finally { client.close(); } conn.disconnect(); stop(); }
From source file:net.myrrix.client.ClientRecommender.java
private void doSetOrRemove(String path, long unnormalizedID, float value, boolean set) throws TasteException { boolean sendValue = value != 1.0f; Map<String, String> requestProperties; byte[] bytes; if (sendValue) { requestProperties = Maps.newHashMapWithExpectedSize(2); bytes = Float.toString(value).getBytes(Charsets.UTF_8); requestProperties.put(HttpHeaders.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString()); requestProperties.put(HttpHeaders.CONTENT_LENGTH, Integer.toString(bytes.length)); } else {//from w ww . j a v a2 s. co m requestProperties = null; bytes = null; } TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(unnormalizedID)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, path, set ? "POST" : "DELETE", sendValue, false, requestProperties); if (sendValue) { OutputStream out = connection.getOutputStream(); out.write(bytes); out.close(); } // Should not be able to return Not Available status if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return; } catch (TasteException te) { log.info("Can't access {} at {}: ({})", path, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", path, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:net.myrrix.client.ClientRecommender.java
/** * @param userIDs users for which recommendations are to be computed * @param howMany desired number of recommendations * @param considerKnownItems if true, items that the user is already associated to are candidates * for recommendation. Normally this is {@code false}. * @param rescorerParams optional parameters to send to the server's {@code RescorerProvider} * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least * @throws NoSuchUserException if <em>none</em> of {@code userIDs} are known in the model. Otherwise unknown * user IDs are ignored.//from w w w. j av a 2 s . c om * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs * @throws UnsupportedOperationException if rescorer is not null */ public List<RecommendedItem> recommendToMany(long[] userIDs, int howMany, boolean considerKnownItems, String[] rescorerParams) throws TasteException { StringBuilder urlPath = new StringBuilder(32); urlPath.append("/recommendToMany"); for (long userID : userIDs) { urlPath.append('/').append(userID); } appendCommonQueryParams(howMany, considerKnownItems, rescorerParams, urlPath); // Note that this assumes that all user IDs are on the same partition. It will fail at request // time if not since the partition of the first user doesn't contain the others. TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(userIDs[0])) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchUserException(Arrays.toString(userIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:net.myrrix.client.ClientRecommender.java
private List<RecommendedItem> anonymousOrSimilar(long[] itemIDs, float[] values, int howMany, String path, String[] rescorerParams, Long contextUserID) throws TasteException { Preconditions.checkArgument(values == null || values.length == itemIDs.length, "Number of values doesn't match number of items"); StringBuilder urlPath = new StringBuilder(); urlPath.append(path);//ww w. j a v a 2 s . c o m for (int i = 0; i < itemIDs.length; i++) { urlPath.append('/').append(itemIDs[i]); if (values != null) { urlPath.append('=').append(values[i]); } } appendCommonQueryParams(howMany, false, rescorerParams, urlPath); // Requests are typically partitioned by user, but this request does not directly depend on a user. // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other // requests related to that user. Otherwise just partition on (first0 item ID, which is at least // deterministic. long idToPartitionOn = contextUserID == null ? itemIDs[0] : contextUserID; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(Arrays.toString(itemIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }