List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.googlecode.fascinator.portal.quartz.ExternalJob.java
/** * The real work happens here/*from w ww. j av a2 s. c o m*/ * */ private void runJob() { HttpURLConnection conn = null; log.debug("Job firing: '{}'", name); try { // Open tasks... much simpler if (token == null) { conn = (HttpURLConnection) url.openConnection(); // Secure tasks } else { String param = "token=" + URLEncoder.encode(token, "UTF-8"); // Prepare our request conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length)); conn.setUseCaches(false); conn.setDoOutput(true); // Send request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(param); wr.flush(); wr.close(); } // Get Response if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { log.error("Error hitting external script: {}", conn.getResponseMessage()); } } catch (IOException ex) { log.error("Error connecting to URL: ", ex); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.handsome.frame.android.volley.stack.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); if (!TextUtils.isEmpty(mUserAgent)) { map.put(HTTP.USER_AGENT, mUserAgent); }/* ww w .jav a 2s .c o m*/ map.putAll(request.getHeaders()); URL parsedUrl = new URL(request.getUrl()); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (HandsomeApplication.getCookies() != null) { HDLog.d(TAG + "-Req-Cookie:", HandsomeApplication.getCookies().toString()); connection.addRequestProperty("Cookie", HandsomeApplication.getCookies()); } else { HDLog.d(TAG + "-Req-Cookie:", "null"); } setConnectionParametersForRequest(connection, request); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey().equalsIgnoreCase("Set-Cookie")) { List<String> cookies = header.getValue(); HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>(); for (String string : cookies) { List<HttpCookie> cookie = HttpCookie.parse(string); for (HttpCookie httpCookie : cookie) { cookieMap.put(httpCookie.getName(), httpCookie); } } HandsomeApplication.setCookies(cookieMap); HDLog.d(TAG + "-Rsp-Cookie:", HandsomeApplication.getCookies().toString()); } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } return response; }
From source file:ai.eve.volley.stack.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); if (!TextUtils.isEmpty(mUserAgent)) { map.put(HTTP.USER_AGENT, mUserAgent); }//from w w w. j a va 2 s . c o m if (!TextUtils.isEmpty(mSignInfo)) { map.put("SIGN", ESecurity.Encrypt(mSignInfo)); } map.putAll(request.getHeaders()); URL parsedUrl = new URL(request.getUrl()); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (EApplication.getCookies() != null) { ELog.I("cookie", EApplication.getCookies().toString()); connection.addRequestProperty("Cookie", EApplication.getReqCookies()); } else { ELog.I("cookie", "null"); } setConnectionParametersForRequest(connection, request); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey().equalsIgnoreCase("Set-Cookie")) { List<String> cookies = header.getValue(); HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>(); for (String string : cookies) { List<HttpCookie> cookie = HttpCookie.parse(string); for (HttpCookie httpCookie : cookie) { if (httpCookie.getDomain() != null && httpCookie.getPath() != null) { cookieMap.put(httpCookie.getName() + httpCookie.getDomain() + httpCookie.getPath(), httpCookie); } else if (httpCookie.getDomain() == null && httpCookie.getPath() != null) { cookieMap.put(httpCookie.getName() + httpCookie.getPath(), httpCookie); } else if (httpCookie.getDomain() != null && httpCookie.getPath() == null) { cookieMap.put(httpCookie.getName() + httpCookie.getDomain(), httpCookie); } else { cookieMap.put(httpCookie.getName(), httpCookie); } } } EApplication.setCookies(cookieMap); if (EApplication.getCookies() != null) { ELog.I("?cookie", EApplication.getCookies().toString()); } } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } return response; }
From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java
/** * Download File from Url in Folder; this method do the same thing that ServerPolling task does, * but i can't call another AsyncTask from class that is not main context. * * @param url/* w ww . java 2 s. c o m*/ * @param folder */ private Boolean downloadFileUrl(String url, File folder) { InputStream input = null; OutputStream output = null; String baseName = FilenameUtils.getBaseName(url); String extension = FilenameUtils.getExtension(url); Log.d(TAG, "FileName: " + baseName + " - FileExt: " + extension); boolean success = true; if (!folder.exists()) { success = folder.mkdir(); } HttpURLConnection connection = null; if (!f.isUrl(url)) return false; Boolean downloadSuccess = false; try { URL Url = new URL(url); connection = (HttpURLConnection) Url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead of the file if ((!url.endsWith(".csv") || !url.endsWith(".txt")) && connection.getResponseCode() != HttpURLConnection.HTTP_OK) { Log.e(TAG, "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage()); return false; } // this will be useful to display download percentage // might be -1: server did not report the length int fileLength = connection.getContentLength(); // download the file input = connection.getInputStream(); output = new FileOutputStream(folder.getAbsolutePath() + "/" + baseName + "." + extension); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { // allow canceling with back button if (isCancelled()) { input.close(); return false; } total += count; output.write(data, 0, count); downloadSuccess = true; } } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return true; }
From source file:it.infn.ct.ToscaIDCInterface.java
/** * Delete deployment having the given UUID. * * @param uuid - Tosca orchestrator UUID *//*from w w w. jav a 2 s. co m*/ protected final void deleteToscaDeployment(final String uuid) { StringBuilder deployment = new StringBuilder(); HttpURLConnection conn; try { URL deploymentEndpoint = new URL(toscaEndPoint.toString() + "/" + uuid); conn = (HttpURLConnection) deploymentEndpoint.openConnection(); conn.setRequestMethod("DELETE"); conn.setRequestProperty("Authorization", "Bearer " + toscaToken); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("charset", "utf-8"); LOG.debug("Orchestrator status code: " + conn.getResponseCode()); LOG.debug("Orchestrator status message: " + conn.getResponseMessage()); if (conn.getResponseCode() == HTTP_204) { LOG.debug("Successfully removed resource: '" + uuid + "'"); } else { LOG.error("Unable to remove resource: '" + uuid + "'"); } } catch (IOException ex) { LOG.error("Connection error with the service at " + toscaEndPoint.toString()); LOG.error(ex); } }
From source file:com.fluidops.iwb.HTMLProvider.HTMLProvider.java
/** * HINT: The gather(List<Statement> res) method collects the statements * extracted by the provider. Use the following guidelinges: * /*from ww w. jav a 2 s . c om*/ * 1.) Make sure to have a clear documentation, structure, and * modularization. Use helper methods wherever possible to increase * readability of the method. * * 2.) Whenever there is a need to create statements, use the helper methods * in {@link ProviderUtils}. This class helps you in generating "safe" URIs, * replacing invalid characters etc. It also offers common functionality for * filtering statements, e.g. removing statements containing null values. * * 3.) Re-use existing ontologies! The {@link Vocabulary} class provides a * mix of vocabulary from common ontologies and can be easily extended. You * should not define URIs inside the provider itself, except these URIs are * absolutely provider-specific. * * 4.) Concerning exception handling, it is best practice to throw * exceptions whenever the provider run cannot be finished in a regular way. * Since these exception will be propagated to the UI, it is recommended to * catch Exceptions locally first, log them, and wrap them into * (Runtime)Exceptions with a human-readable description. When logging * exceptions, the log level "warn" is appropriate. */ @Override public void gather(List<Statement> res) throws Exception { URL registryUrl = new URL(config.location); HttpURLConnection registryConnection = (HttpURLConnection) registryUrl.openConnection(); registryConnection.setRequestMethod("GET"); // ////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////// STEP // 1 logger.info("Retrieving packages from CKAN..."); if (registryConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { String msg = "Connection with the registry could not be established. (" + registryConnection.getResponseCode() + ", " + registryConnection.getResponseMessage() + ")"; logger.warn(msg); throw new RuntimeException(msg); // propagate to UI } String siteContent = GenUtil.readUrl(registryConnection.getInputStream()); JSONObject groupAsJson = null; JSONArray packageListJsonArray = null; try { groupAsJson = new JSONObject(new JSONTokener(siteContent)); packageListJsonArray = groupAsJson.getJSONArray("packages"); } catch (JSONException e) { String msg = "Returned content " + siteContent + " is not valid JSON. Check if the registry URL is valid."; logger.warn(msg); throw new RuntimeException(msg); // propagate to UI } logger.info("-> found " + packageListJsonArray.length() + " packages"); // ////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////// STEP // 2 logger.info("Registering LOD catalog in metadata repository"); /** * HINT: the method createStatement allows to create statements if * subject, predicate and object are all known; use this method instead * of opening a value factory */ res.add(ProviderUtils.createStatement(CKANVocabulary.CKAN_CATALOG, RDF.TYPE, Vocabulary.DCAT.CATALOG)); res.add(ProviderUtils.createStatement(CKANVocabulary.CKAN_CATALOG, RDFS.LABEL, CKANVocabulary.CKAN_CATALOG_LABEL)); logger.info("-> done"); // ////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////// STEP // 3 logger.info("Extracting metdata for the individual data sets listed in CKAN"); /** * HINT: Set up an Apache HTTP client with a manager for multiple * threads; as a general guideline, use parallelization whenever * crawling web sources! */ MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(connectionManager); ExecutorService pool = Executors.newFixedThreadPool(10); // we store the data in a temporary memory store, which allows us // to perform transformation on the result set Repository repository = null; RepositoryConnection connection = null; try { // initialize repository and connection repository = new SailRepository(new MemoryStore()); repository.initialize(); connection = repository.getConnection(); // Fire up a thread for every package logger.info("-> Fire up threads for the individual packages..."); for (int i = 0; i < packageListJsonArray.length(); i++) { // we use the JSON representation to get a base URI to resolve // relative // URIs in the XML later on. (and a fallback solution) String host = "http://www.ckan.net/package/" + packageListJsonArray.get(i).toString(); String baseUri = findBaseUri( "http://www.ckan.net/api/rest/package/" + packageListJsonArray.get(i).toString()); baseUri = (baseUri == null) ? host : baseUri; pool.execute(new MetadataReader(client, host, baseUri, CKANVocabulary.CKAN_CATALOG, connection)); } logger.info("-> Waiting for all tasks to complete (" + packageListJsonArray.length() + "tasks/data sources)..."); pool.shutdown(); pool.awaitTermination(4, TimeUnit.HOURS); /** * Now the extraction has finished, all statements are available in * our temporary repository. We apply some conversions and * transformations to align the extracted statements with our target * ontology. * * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * !!!!!!!!!!!!! !!! NOTE: this code is /NOT/ best practice, we * should eventually extend !!! !!! ProviderUtils to deal with at * least lightweight transformations !!! !!! (such as changing * property names) or realize such tasks using !!! !!! an integrated * mapping framework. !!! * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ // Extraction from temporary repository, phase 1: logger.info( "-> Extract dcterms:title AS rdfs:label, dcterms:contributor AS dcterms:creator, and dcterms:rights AS dcterms:license"); String mappingQuery = mappingQuery(); GraphQuery mappingGraphQuery = connection.prepareGraphQuery(QueryLanguage.SPARQL, mappingQuery); GraphQueryResult result = mappingGraphQuery.evaluate(); logger.info("-> Appending extracted result to statement list"); ProviderUtils.appendGraphQueryResultToListAndClose(result, res); // Label the distribution nodes logger.info("-> Generate labels for distributions"); String labelDistributionQuery = labelDistributionQuery(); GraphQuery labelDistributionGraphQuery = connection.prepareGraphQuery(QueryLanguage.SPARQL, labelDistributionQuery); GraphQueryResult result2 = labelDistributionGraphQuery.evaluate(); logger.info("-> Appending extracted result to statement list"); ProviderUtils.appendGraphQueryResultToListAndClose(result2, res); // Extraction from temporary repository, phase 2: logger.info("-> Deleting previously extracted triples and additional, not required information..."); String deleteQuery = deleteQuery(); Update deleteGraphQuery = connection.prepareUpdate(QueryLanguage.SPARQL, deleteQuery); deleteGraphQuery.execute(); // Extraction from temporary repository, phase 3: logger.info("-> Deleting dcat:distribution and dcat:accessUrl information from" + "temp repository for which format information is missing..."); String cleanDistQuery = cleanDistQuery(); Update cleanupGraphQuery = connection.prepareUpdate(QueryLanguage.SPARQL, cleanDistQuery); cleanupGraphQuery.execute(); logger.info("-> Appending remaining statements to result..."); connection.getStatements(null, null, null, false).addTo(res); logger.info("Provider run finished successfully"); } catch (Exception e) { logger.warn(e.getMessage()); throw new RuntimeException(e); } finally { if (connection != null) connection.close(); if (repository != null) repository.shutDown(); } // in the end, make sure there are no statements containing null in // any of the position (did not take special care when creating // statements) logger.info("-> cleaning up null statements"); res = ProviderUtils.filterNullStatements(res); }
From source file:org.andstatus.app.net.http.HttpConnectionOAuthJavaNet.java
/** * Partially borrowed from the "Impeller" code ! *//*from ww w . j a v a 2 s. co m*/ @Override public void registerClient(String path) throws ConnectionException { String logmsg = "registerClient; for " + data.originUrl + "; URL='" + pathToUrlString(path) + "'"; MyLog.v(this, logmsg); String consumerKey = ""; String consumerSecret = ""; data.oauthClientKeys.clear(); Writer writer = null; try { URL endpoint = new URL(pathToUrlString(path)); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); Map<String, String> params = new HashMap<String, String>(); params.put("type", "client_associate"); params.put("application_type", "native"); params.put("redirect_uris", HttpConnection.CALLBACK_URI.toString()); params.put("client_name", HttpConnection.USER_AGENT); params.put("application_name", HttpConnection.USER_AGENT); String requestBody = HttpConnectionUtils.encode(params); conn.setDoOutput(true); conn.setDoInput(true); writer = new OutputStreamWriter(conn.getOutputStream(), UTF_8); writer.write(requestBody); writer.close(); if (conn.getResponseCode() != 200) { String msg = HttpConnectionUtils.readStreamToString(conn.getErrorStream()); MyLog.i(this, "Server returned an error response: " + msg); MyLog.i(this, "Server returned an error response: " + conn.getResponseMessage()); } else { String response = HttpConnectionUtils.readStreamToString(conn.getInputStream()); JSONObject jso = new JSONObject(response); if (jso != null) { consumerKey = jso.getString("client_id"); consumerSecret = jso.getString("client_secret"); data.oauthClientKeys.setConsumerKeyAndSecret(consumerKey, consumerSecret); } } } catch (IOException e) { MyLog.i(this, logmsg, e); } catch (JSONException e) { MyLog.i(this, logmsg, e); } finally { DbUtils.closeSilently(writer); } if (data.oauthClientKeys.areKeysPresent()) { MyLog.v(this, "Completed " + logmsg); } else { throw ConnectionException.fromStatusCodeAndHost(StatusCode.NO_CREDENTIALS_FOR_HOST, "No client keys for the host yet; " + logmsg, data.originUrl); } }
From source file:org.jmxtrans.embedded.output.StackdriverWriter.java
/** * Send given metrics to the Stackdriver server using HTTP * // w ww . j a v a 2 s. c o m * @param results * Iterable collection of data points */ @Override public void write(Iterable<QueryResult> results) { logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results); HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(stackdriverApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey); serialize(results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200 && responseCode != 201) { exceptionCounter.incrementAndGet(); logger.warn("Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}", responseCode, urlConnection.getResponseMessage(), url, proxy); } if (logger.isTraceEnabled()) { IoUtils2.copy(urlConnection.getInputStream(), System.out); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Failure to send result to Stackdriver server '{}' with proxy {}", url, proxy, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } urlConnection.disconnect(); } catch (IOException e) { logger.warn("Error flushing http connection for one result, continuing"); logger.debug("Stack trace for the http connection, usually a network timeout", e); } } } }
From source file:co.aikar.timings.TimingsExport.java
@Override public void run() { out.put("data", toArrayMapper(history, TimingHistory::export)); String response = null;/*from www .ja va2s. c o m*/ String timingsURL = null; try { HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection(); con.setDoOutput(true); String hostName = "BrokenHost"; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception ignored) { } con.setRequestProperty("User-Agent", "Paper/" + Bukkit.getServerName() + "/" + hostName); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); OutputStream request = new GZIPOutputStream(con.getOutputStream()) { { this.def.setLevel(7); } }; request.write(JSONValue.toJSONString(out).getBytes("UTF-8")); request.close(); response = getResponse(con); if (con.getResponseCode() != 302) { listeners.sendMessage( ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage()); listeners.sendMessage(ChatColor.RED + "Check your logs for more information"); if (response != null) { Bukkit.getLogger().log(Level.SEVERE, response); } return; } timingsURL = con.getHeaderField("Location"); listeners.sendMessage(ChatColor.GREEN + "View Timings Report: " + timingsURL); if (response != null && !response.isEmpty()) { Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response); } } catch (IOException ex) { listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information"); if (response != null) { Bukkit.getLogger().log(Level.SEVERE, response); } Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex); } finally { this.listeners.done(timingsURL); } }
From source file:com.apache.ivy.BasicURLHandler.java
public void upload(File source, URL dest, CopyProgressListener l) throws IOException { if (!"http".equals(dest.getProtocol()) && !"https".equals(dest.getProtocol())) { throw new UnsupportedOperationException("URL repository only support HTTP PUT at the moment"); }/* ww w . ja v a 2 s . c o m*/ // Install the IvyAuthenticator IvyAuthenticator.install(); HttpURLConnection conn = null; try { dest = normalizeToURL(dest); conn = (HttpURLConnection) dest.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("User-Agent", "Apache Ivy/1.0");// + Ivy.getIvyVersion()); conn.setRequestProperty("Content-type", "application/octet-stream"); conn.setRequestProperty("Content-length", Long.toString(source.length())); conn.setInstanceFollowRedirects(true); InputStream in = new FileInputStream(source); try { OutputStream os = conn.getOutputStream(); FileUtil.copy(in, os, l); } finally { try { in.close(); } catch (IOException e) { /* ignored */ } } validatePutStatusCode(dest, conn.getResponseCode(), conn.getResponseMessage()); } finally { disconnect(conn); } }