List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:org.openrdf.http.server.ProtocolTest.java
private void putFile(String location, String file) throws Exception { System.out.println("Put file to " + location); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true);// ww w . jav a 2 s .c o m RDFFormat dataFormat = Rio.getParserFormatForFileName(file).orElse(RDFFormat.RDFXML); conn.setRequestProperty("Content-Type", dataFormat.getDefaultMIMEType()); InputStream dataStream = ProtocolTest.class.getResourceAsStream(file); try { OutputStream connOut = conn.getOutputStream(); try { IOUtil.transfer(dataStream, connOut); } finally { connOut.close(); } } finally { dataStream.close(); } conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK && // 200 OK responseCode != HttpURLConnection.HTTP_NO_CONTENT) // 204 NO CONTENT { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); } }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
private void putFile(String location, String file) throws Exception { System.out.println("Put file to " + location); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true);// ww w. ja va 2s . c om RDFFormat dataFormat = Rio.getParserFormatForFileName(file).orElse(RDFFormat.RDFXML); conn.setRequestProperty("Content-Type", dataFormat.getDefaultMIMEType()); InputStream dataStream = ProtocolTest.class.getResourceAsStream(file); try { OutputStream connOut = conn.getOutputStream(); try { IOUtil.transfer(dataStream, connOut); } finally { connOut.close(); } } finally { dataStream.close(); } conn.connect(); int responseCode = conn.getResponseCode(); // HTTP 200 or 204 if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NO_CONTENT) { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); } }
From source file:com.cgxlib.xq.rebind.JsniBundleGenerator.java
/** * Get the content of a javascript source. It supports remote sources hosted in CDN's. *///from ww w. java 2 s . co m private String getContent(TreeLogger logger, String path, String src) throws UnableToCompleteException { HttpURLConnection connection = null; InputStream in = null; try { if (!src.matches("(?i)https?://.*")) { String file = path + "/" + src; logger.log(TreeLogger.INFO, getClass().getSimpleName() + " - importing external javascript: " + file); in = this.getClass().getClassLoader().getResourceAsStream(file); if (in == null) { logger.log(TreeLogger.ERROR, "Unable to read javascript file: " + file); } } else { logger.log(TreeLogger.INFO, getClass().getSimpleName() + " - downloading external javascript: " + src); URL url = new URL(src); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Encoding", "gzip, deflate"); connection.setRequestProperty("Host", url.getHost()); connection.setConnectTimeout(3000); connection.setReadTimeout(3000); int status = connection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { logger.log(TreeLogger.ERROR, "Server Error: " + status + " " + connection.getResponseMessage()); throw new UnableToCompleteException(); } String encoding = connection.getContentEncoding(); in = connection.getInputStream(); if ("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else if ("deflate".equalsIgnoreCase(encoding)) { in = new InflaterInputStream(in); } } return inputStreamToString(in); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Error: " + e.getMessage()); throw new UnableToCompleteException(); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.runnerup.export.EndomondoSynchronizer.java
@Override public Status connect() { if (isConfigured()) { return Status.OK; }/*from ww w .ja v a 2 s .c o m*/ Status s = Status.NEED_AUTH; s.authMethod = Synchronizer.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } /** * Generate deviceId */ deviceId = UUID.randomUUID().toString(); Exception ex = null; HttpURLConnection conn = null; logout(); try { /** * */ String login = AUTH_URL; FormValues kv = new FormValues(); kv.put("email", username); kv.put("password", password); kv.put("v", "2.4"); kv.put("action", "pair"); kv.put("deviceId", deviceId); kv.put("country", "N/A"); conn = (HttpURLConnection) new URL(login).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); JSONObject res = parseKVP(in); conn.disconnect(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == HttpStatus.SC_OK && "OK".contentEquals(res.getString("_0")) && res.has("authToken")) { authToken = res.getString("authToken"); return Status.OK; } Log.e(getName(), "FAIL: code: " + responseCode + ", msg=" + amsg + ", res=" + res.toString()); return s; } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } if (conn != null) conn.disconnect(); s = Synchronizer.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:it.baywaylabs.jumpersumo.utility.Finder.java
private Boolean downloadFileUrl(String url, File folder) { InputStream input = null;//from w ww . ja va 2 s . co m 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 (!this.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) { 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:org.eclipse.rdf4j.http.server.ProtocolTest.java
@Test public void testQueryResponse_HEAD() throws Exception { String query = "DESCRIBE <foo:bar>"; String location = TestServer.REPOSITORY_URL; location += "?query=" + URLEncoder.encode(query, "UTF-8"); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); // Request RDF/XML formatted results: conn.setRequestProperty("Accept", RDFFormat.RDFXML.getDefaultMIMEType()); conn.connect();/* w w w. j a v a2s .c o m*/ try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String contentType = conn.getHeaderField("Content-Type"); assertNotNull(contentType); // snip off optional charset declaration int charPos = contentType.indexOf(";"); if (charPos > -1) { contentType = contentType.substring(0, charPos); } assertEquals(RDFFormat.RDFXML.getDefaultMIMEType(), contentType); assertEquals(0, conn.getContentLength()); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
From source file:io.github.retz.web.Client.java
public int getBinaryFile(int id, String file, OutputStream out) throws IOException { String date = TimestampHelper.now(); String resource = "/job/" + id + "/download?path=" + file; AuthHeader header = authenticator.header("GET", "", date, resource); URL url = new URL(uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + resource); // TODO url-encode! LOG.info("Fetching {}", url); HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); //LOG.info("classname> {}", conn.getClass().getName()); if (uri.getScheme().equals("https") && !checkCert && conn instanceof HttpsURLConnection) { if (verboseLog) { LOG.warn(/* w ww .j a va 2 s . c o m*/ "DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message."); } HttpsURLConnection sslCon = (HttpsURLConnection) conn; if (socketFactory != null) { sslCon.setSSLSocketFactory(socketFactory); } if (hostnameVerifier != null) { sslCon.setHostnameVerifier(hostnameVerifier); } } conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/octet-stream"); conn.setRequestProperty("Authorization", header.buildHeader()); conn.setRequestProperty("Date", date); conn.setRequestProperty("Content-md5", ""); conn.setDoInput(true); String s2s = authenticator.string2sign("GET", "", date, resource); LOG.debug("Authorization: {} / S2S={}", header.buildHeader(), s2s); if (conn.getResponseCode() != 200) { if (verboseLog) { LOG.warn("HTTP Response:", conn.getResponseMessage()); } if (conn.getResponseCode() < 200) { throw new AssertionError(conn.getResponseMessage()); } else if (conn.getResponseCode() == 404) { throw new FileNotFoundException(url.toString()); } else { String message; try { Response response = MAPPER.readValue(conn.getErrorStream(), Response.class); message = response.status(); LOG.error(message, response); } catch (JsonProcessingException e) { message = e.toString(); LOG.error(message, e); } throw new UnknownError(message); } } int size = conn.getContentLength(); if (size < 0) { throw new IOException("Illegal content length:" + size); } else if (size == 0) { // not bytes to save; return 0; } try { return IOUtils.copy(conn.getInputStream(), out); } finally { conn.disconnect(); } }
From source file:JavaTron.AudioTron.java
/** * Send a get request to the AudioTron server * * @param address the uri to use/* w w w . j a v a2 s.c o m*/ * @param args the arguments to use * @param parser an optional line-by-line parser to use instead of buffering * the whole response * * @return null on success, a string on error. The string describes * the error. * * @throws IOException if the process was interrupted */ protected String get(String address, Vector args, Parser parser) throws IOException { String ret = null; StringBuffer myAddress = new StringBuffer(); Object[] methodArgs = new Object[1]; try { // construct the address myAddress.append(address); if (args != null) { myAddress.append('?'); createURIArgs(myAddress, args); } if (showAddress) { System.out.println(myAddress.toString()); } HttpURLConnection conn = getConnection(myAddress.toString()); if (conn.getResponseCode() != 200 && conn.getResponseCode() != 302) { try { ret = conn.getResponseMessage(); } catch (IOException ioe) { ioe.printStackTrace(); } if (ret == null) { ret = "Unknown Error"; } if (parser != null) { parser.begin(ret); } return ret; } isr = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(isr); String s; getBuffer = new StringBuffer(); if (parser != null) { parser.begin(null); } while ((s = reader.readLine()) != null) { if (showGet) { System.out.println(s); } getBuffer.append(s); getBuffer.append("\n"); if (parser == null) { // getBuffer.append(s); } else { if (!parser.parse(s)) { return "Parse Error"; } } } if (parser == null && showUnparsedOutput) { System.out.println(getBuffer); } if (parser != null) { parser.end(false); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { // if this happens, call the parse method if there is a parser // with a null value to indicate an error if (parser != null) { parser.end(true); } throw (ioe); } finally { try { isr.close(); } catch (Exception e) { // this is ok } } //return getBuffer.toString(); return ret; }
From source file:edwardawebb.queueman.classes.NetFlix.java
/** * // www . ja v a 2 s .c o m * @param queueType * @param maxResults * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions */ public int getHomeTitlesJSON() { times[2] = System.currentTimeMillis(); URL QueueUrl = null; int result = NF_ERROR_BAD_DEFAULT; String expanders = "?expand=synopsis,formats&output=json"; InputStream is = null; try { //if (!NetFlix.homeQueue.isEmpty()) // return 200; QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/at_home" + expanders); Log.d("NetFlix", "" + QueueUrl.toString()); setSignPost(user.getAccessToken(), user.getAccessTokenSecret()); HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection(); NetFlix.oaconsumer.sign(request); request.connect(); lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage(); result = request.getResponseCode(); is = request.getInputStream(); JSON2Queue.parseAtHome(is); /* BufferedReader in = new BufferedReader(new InputStreamReader(is)); String linein = null; while ((linein = in.readLine()) != null) { Log.d("NetFlixQueue", "" + linein); }*/ } catch (IOException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "IO Error connecting to NetFlix queue") } catch (OAuthMessageSignerException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "Unable to Sign request - token invalid") } catch (OAuthExpectationFailedException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "Expectation failed") } times[3] = System.currentTimeMillis(); Log.d("Performance", "XML: " + (times[1] - times[0]) + " | JSON: " + (times[3] - times[2])); return result; }
From source file:edwardawebb.queueman.classes.NetFlix.java
/** * /*from w w w . j a v a 2 s .c o m*/ * @param queueType * @param maxResults * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions */ public int getHomeTitles() { URL QueueUrl = null; int result = NF_ERROR_BAD_DEFAULT; String expanders = "?expand=synopsis,formats"; InputStream xml = null; try { if (!NetFlix.homeQueue.isEmpty()) return 200; QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/at_home" + expanders); HomeQueueHandler myHandler = new HomeQueueHandler(); Log.d("NetFlix", "" + QueueUrl.toString()); setSignPost(user.getAccessToken(), user.getAccessTokenSecret()); HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection(); NetFlix.oaconsumer.sign(request); request.connect(); lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage(); result = request.getResponseCode(); xml = request.getInputStream(); /*BufferedReader in = new BufferedReader(new InputStreamReader(xml)); String linein = null; while ((linein = in.readLine()) != null) { Log.d("NetFlixQueue", "" + linein); }*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(myHandler); xr.parse(new InputSource(xml)); } catch (ParserConfigurationException e) { reportError(e, lastResponseMessage); } catch (SAXException e) { reportError(e, lastResponseMessage); } catch (IOException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "IO Error connecting to NetFlix queue") } catch (OAuthMessageSignerException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "Unable to Sign request - token invalid") } catch (OAuthExpectationFailedException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "Expectation failed") } return result; }