List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:edu.lternet.pasta.dml.download.DownloadHandler.java
/** * Gets content from given source and writes it to DataStorageInterface * to store them. This method will be called by run() * //from w w w.ja v a 2 s . c om * @param resourceName the URL to the source data to be retrieved */ protected boolean getContentFromSource(String resourceName) { boolean successFlag = false; QualityCheck onlineURLsQualityCheck = null; boolean onlineURLsException = false; // used to determine status of onlineURLs quality check if (resourceName != null) { resourceName = resourceName.trim(); } if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://") || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) { // get the data from a URL int responseCode = 0; String responseMessage = null; try { URL url = new URL(resourceName); boolean isFTP = false; if (entity != null) { String contentType = null; // Find the right MIME type and set it as content type if (resourceName.startsWith("http")) { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("HEAD"); httpURLConnection.connect(); contentType = httpURLConnection.getContentType(); responseCode = httpURLConnection.getResponseCode(); responseMessage = httpURLConnection.getResponseMessage(); } else if (resourceName.startsWith("file")) { URLConnection urlConnection = url.openConnection(); urlConnection.connect(); contentType = urlConnection.getContentType(); } else { // FTP isFTP = true; contentType = "application/octet-stream"; } entity.setUrlContentType(contentType); } if (!isFTP) { // HTTP(S) or FILE InputStream filestream = url.openStream(); try { successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream); } catch (IOException e) { exception = e; String errorMessage = e.getMessage(); if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) { onlineURLsException = true; } } finally { filestream.close(); } } else { // FTP String[] urlParts = resourceName.split("/"); String address = urlParts[2]; String dir = "/"; for (int i = 3; i < urlParts.length - 1; i++) { dir += urlParts[i] + "/"; } String fileName = urlParts[urlParts.length - 1]; FTPClient ftpClient = new FTPClient(); ftpClient.connect(address); ftpClient.login(ANONYMOUS, anonymousFtpPasswd); ftpClient.changeWorkingDirectory(dir); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking InputStream filestream = ftpClient.retrieveFileStream(fileName); try { successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream); } catch (IOException e) { exception = e; String errorMessage = e.getMessage(); if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) { onlineURLsException = true; } } finally { try { filestream.close(); } catch (IOException e) { exception = new DataSourceNotFoundException(String .format("Error closing local file '%s': %s", resourceName, e.getMessage())); onlineURLsException = true; } } // logout and disconnect if FTP session if (resourceName.startsWith("ftp") && ftpClient != null) { try { ftpClient.enterLocalActiveMode(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { exception = new DataSourceNotFoundException( String.format("Error disconnecting from FTP with resource '%s': %s", resourceName, e.getMessage())); onlineURLsException = true; } } } } catch (MalformedURLException e) { String eClassName = e.getClass().getName(); String eMessage = String.format("%s: %s", eClassName, e.getMessage()); onlineURLsException = true; exception = new DataSourceNotFoundException( String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage)); } catch (IOException e) { String eClassName = e.getClass().getName(); String eMessage = String.format("%s: %s", eClassName, e.getMessage()); if (responseCode > 0) { eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage); } onlineURLsException = true; exception = new DataSourceNotFoundException( String.format("The URL '%s' is not reachable: %s", resourceName, eMessage)); } // Initialize the "Online URLs are live" quality check String qualityCheckIdentifier = "onlineURLs"; QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier); onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate); if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) { String resourceNameEscaped = embedInCDATA(resourceName); if (!onlineURLsException) { onlineURLsQualityCheck.setStatus(Status.valid); onlineURLsQualityCheck.setFound("true"); onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped); } else { onlineURLsQualityCheck.setFailedStatus(); onlineURLsQualityCheck.setFound("false"); String explanation = "Failed to access URL: " + resourceNameEscaped; explanation = explanation + "; " + embedInCDATA(exception.getMessage()); onlineURLsQualityCheck.setExplanation(explanation); } entity.addQualityCheck(onlineURLsQualityCheck); } return successFlag; } else if (resourceName != null && resourceName.startsWith("ecogrid://")) { // get the docid from url int start = resourceName.indexOf("/", 11) + 1; //log.debug("start: " + start); int end = resourceName.indexOf("/", start); if (end == -1) { end = resourceName.length(); } //log.debug("end: " + end); String ecogridIdentifier = resourceName.substring(start, end); // pass this docid and get data item //System.out.println("the endpoint is "+ECOGRIDENDPOINT); //System.out.println("The identifier is "+ecogridIdentifier); //return false; return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier); } else if (resourceName != null && resourceName.startsWith("srb://")) { // get srb docid from the url String srbIdentifier = transformSRBurlToDocid(resourceName); // reset endpoint for srb (This is hack we need to figure ou // elegent way to do this //mEndPoint = Config.getValue("//ecogridService/srb/endPoint"); // pass this docid and get data item //log.debug("before get srb data"); return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier); } else { successFlag = false; return successFlag; } }
From source file:it.infn.ct.ToscaIDCInterface.java
/** * Return deployment information of a given tUUID. * * @param uuid - TOSCA UUID// ww w . j a v a 2s .c om * @param token - Orchestrator access token * @return Orchestrator deployment information */ protected final String getToscaDeployment(final String uuid, final String token) { StringBuilder deployment = new StringBuilder(); HttpURLConnection conn; URL deploymentEndpoint = null; try { LOG.debug("endpoint: '" + toscaEndPoint + "'"); deploymentEndpoint = new URL(toscaEndPoint.toString() + "/" + uuid); LOG.debug("deploymentEndpoint: '" + deploymentEndpoint + "'"); conn = (HttpURLConnection) deploymentEndpoint.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Bearer " + token); 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_200) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String ln; while ((ln = br.readLine()) != null) { deployment.append(ln); } LOG.debug("Orchestrator result: " + deployment); } } catch (IOException ex) { LOG.error("Connection error with the service at " + deploymentEndpoint.toString()); LOG.error(ex); } return deployment.toString(); }
From source file:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private <T> T call(HttpURLConnection conn, Map jsonOutput, int expectedResponse, Class<T> klass, int authRetryCount) throws IOException { T ret = null;//from ww w.ja va2 s. c om try { if (jsonOutput != null) { writeJson(jsonOutput, conn.getOutputStream()); } } catch (IOException ex) { IOUtils.closeStream(conn.getInputStream()); throw ex; } if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) || conn.getResponseMessage().contains(INVALID_SIGNATURE))) || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // Ideally, this should happen only when there is an Authentication // failure. Unfortunately, the AuthenticationFilter returns 403 when it // cannot authenticate (Since a 401 requires Server to send // WWW-Authenticate header as well).. KMSClientProvider.this.authToken = new DelegationTokenAuthenticatedURL.Token(); if (authRetryCount > 0) { String contentType = conn.getRequestProperty(CONTENT_TYPE); String requestMethod = conn.getRequestMethod(); URL url = conn.getURL(); conn = createConnection(url, requestMethod); conn.setRequestProperty(CONTENT_TYPE, contentType); return call(conn, jsonOutput, expectedResponse, klass, authRetryCount - 1); } } try { AuthenticatedURL.extractToken(conn, authToken); } catch (AuthenticationException e) { // Ignore the AuthExceptions.. since we are just using the method to // extract and set the authToken.. (Workaround till we actually fix // AuthenticatedURL properly to set authToken post initialization) } HttpExceptionUtils.validateResponse(conn, expectedResponse); if (conn.getContentType() != null && conn.getContentType().trim().toLowerCase().startsWith(APPLICATION_JSON_MIME) && klass != null) { ObjectMapper mapper = new ObjectMapper(); InputStream is = null; try { is = conn.getInputStream(); ret = mapper.readValue(is, klass); } finally { IOUtils.closeStream(is); } } return ret; }
From source file:org.runnerup.export.RunKeeperSynchronizer.java
@Override public Status upload(SQLiteDatabase db, final long mID) { Status s;// w w w . j av a 2s. c o m if ((s = connect()) != Status.OK) { return s; } /** * Get the fitnessActivities end-point */ HttpURLConnection conn = null; Exception ex; try { URL newurl = new URL(REST_URL + fitnessActivitiesUrl); Log.e(Constants.LOG, "url: " + newurl.toString()); conn = (HttpURLConnection) newurl.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Authorization", "Bearer " + access_token); conn.addRequestProperty("Content-type", "application/vnd.com.runkeeper.NewFitnessActivity+json"); RunKeeper rk = new RunKeeper(db); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); rk.export(mID, w); w.flush(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); conn.disconnect(); conn = null; if (responseCode >= HttpStatus.SC_OK && responseCode < HttpStatus.SC_MULTIPLE_CHOICES) { s = Status.OK; s.activityId = mID; return s; } ex = new Exception(amsg); } catch (Exception e) { ex = e; } if (ex != null) { Log.e(getName(), "Failed to upload: " + ex.getMessage()); } if (conn != null) { conn.disconnect(); } s = Synchronizer.Status.ERROR; s.ex = ex; s.activityId = mID; return s; }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
/** * Checks that the requested content type is returned when accept header explicitly set. *//*from w w w. j av a 2 s . co m*/ @Test public void testContentTypeForGraphQuery1_GET() 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(); // Request RDF/XML formatted results: conn.setRequestProperty("Accept", RDFFormat.RDFXML.getDefaultMIMEType()); conn.connect(); 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); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
From source file:com.hackerati.android.user_sdk.volley.HHurlStack.java
@Override public HttpResponse performRequest(final Request<?> request, final Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); final HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from w ww . j av a2 s . c om*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { final String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } final URL parsedUrl = new URL(url); final HttpURLConnection connection = openConnection(parsedUrl, request); for (final String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. final ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode; try { // Will throw IOException if server responds with 401. responseCode = connection.getResponseCode(); } catch (final IOException e) { // Will return 401, because now connection has the correct internal // state. 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."); } final StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); final BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (final Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { final Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:it.infn.ct.ToscaIDCInterface.java
/** * Submit template to the orchestrator a template. * @return TOSCA UUID//from w ww . j ava2 s . com */ public final String submitOrchestrator() { StringBuilder orchestratorResult = new StringBuilder(""); StringBuilder postData = new StringBuilder(); String toscParametersValues = ""; String toscaParametersJson = ""; String tUUID = ""; String[] toscaParams = toscaParameters.split("&"); String tParams = ""; for (int i = 0; i < toscaParams.length; i++) { String[] paramArgs = toscaParams[i].split("="); if (paramArgs[0].trim().equals("params")) { toscaParametersJson = toscaCommand.getActionInfo() + FS + paramArgs[1].trim(); LOG.debug("Loading params json file: '" + toscaParametersJson + "'"); try { String paramsJson = new String(Files.readAllBytes(Paths.get(toscaParametersJson))); LOG.debug("params JSON: '" + paramsJson + "'"); toscParametersValues = getDocumentValue(paramsJson, "parameters"); LOG.debug("extracted parameters: '" + tParams + "'"); } catch (IOException ex) { LOG.error("Parameters json file '" + toscaParametersJson + "' is not readable"); LOG.error(ex); } catch (ParseException ex) { LOG.error("Parameters json file '" + toscaParametersJson + "' is not parseable"); LOG.error(ex); } LOG.debug("Parameters json file '" + toscaParametersJson + "' successfully parsed"); break; } } if (toscParametersValues.length() > 0) { tParams = "\"parameters\": " + toscParametersValues + ", "; } postData.append("{ " + tParams + "\"template\": \""); String toscaTemplateContent = ""; LOG.debug("Escaping toscaTemplate file '" + toscaTemplate + "'"); try { toscaTemplateContent = new String(Files.readAllBytes(Paths.get(toscaTemplate))).replace("\n", "\\n"); } catch (IOException ex) { LOG.error("Template '" + toscaTemplate + "'is not readable"); LOG.error(ex); } postData.append(toscaTemplateContent); postData.append("\" }"); LOG.debug("JSON Data (begin):\n" + postData + "\nJSON Data (end)"); HttpURLConnection conn; String orchestratorDoc = ""; try { conn = (HttpURLConnection) toscaEndPoint.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + toscaToken); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("charset", "utf-8"); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postData.toString()); wr.flush(); wr.close(); LOG.debug("Orchestrator status code: " + conn.getResponseCode()); LOG.debug("Orchestrator status message: " + conn.getResponseMessage()); if (conn.getResponseCode() == HTTP_201) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); orchestratorResult = new StringBuilder(); String ln; while ((ln = br.readLine()) != null) { orchestratorResult.append(ln); } LOG.debug("Orchestrator result: " + orchestratorResult); orchestratorDoc = orchestratorResult.toString(); tUUID = getDocumentValue(orchestratorDoc, "uuid"); LOG.debug("Created resource has UUID: '" + tUUID + "'"); } else { LOG.warn("Orchestrator return code is: " + conn.getResponseCode()); } } catch (IOException ex) { LOG.error("Connection error with the service at " + toscaEndPoint.toString()); LOG.error(ex); } catch (ParseException ex) { LOG.error("Error parsing JSON:" + orchestratorDoc); LOG.error(ex); } return tUUID; }
From source file:androhashcheck.MainFrame.java
/** * Upolads file on server for given path as a String. * * @param fileName//from ww w. j av a 2 s . c o m */ public void upoloadFile(String fileName) { try { String url = ConfigClass.serverURL + "/api/upload_task"; URL obj = new URL(url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(new File(fileName)); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty("token", ConfigClass.token); try (OutputStream out = connection.getOutputStream()) { multipartEntity.writeTo(out); } int status = connection.getResponseCode(); System.out.println(status); System.out.println(connection.getResponseMessage()); StringBuilder response; try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String inputLine; response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } updateStatus(fileName + " done uploading, server response: " + response); if (status == 200) { shouldCheckTasks = true; String taskId = response.toString().replace("}", "").split(":")[1].trim(); TaskObject newTask = new TaskObject(); newTask.setFileName(fileName); newTask.setTaskId(taskId); taskList.add(newTask); } } catch (Exception ex) { updateStatus("error with uploading " + fileName); Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.runnerup.export.GarminSynchronizer.java
@Override public void downloadWorkout(File dst, String key) throws Exception { HttpURLConnection conn = null; Exception ex = null;//from www .j av a 2 s .c o m FileOutputStream out = null; try { conn = (HttpURLConnection) new URL(GET_WORKOUT_URL + key).openConnection(); conn.setRequestMethod(RequestMethod.GET.name()); addCookies(conn); conn.connect(); getCookies(conn); InputStream in = new BufferedInputStream(conn.getInputStream()); out = new FileOutputStream(dst); int cnt = 0; byte buf[] = new byte[1024]; while (in.read(buf) > 0) { cnt += buf.length; out.write(buf); } Log.e(getName(), "downloaded workout key: " + key + " " + cnt + " bytes from " + getName()); in.close(); out.close(); conn.disconnect(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == HttpStatus.SC_OK) { return; } ex = new Exception(amsg); } catch (Exception e) { ex = e; } if (conn != null) { try { conn.disconnect(); } catch (Exception e) { } } if (out != null) { try { out.close(); } catch (Exception e) { } } ex.printStackTrace(); throw ex; }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Send a file via HTTP POST with basic authentication. * //from w ww.jav a 2s.co m * @param urlStr the server url to POST to. * @param file the file to send. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the return string from the POST. * @throws Exception */ public static String sendFilePost(String urlStr, File file, String user, String password) throws Exception { BufferedOutputStream wr = null; FileInputStream fis = null; HttpURLConnection conn = null; try { fis = new FileInputStream(file); long fileSize = file.length(); // Authenticator.setDefault(new Authenticator(){ // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication("test", "test".toCharArray()); // } // }); conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(true); // conn.setRequestProperty("Accept-Encoding", "gzip "); // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Type", "application/x-zip-compressed"); // conn.setRequestProperty("Content-Length", "" + fileSize); // conn.setRequestProperty("Connection", "Keep-Alive"); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); wr = new BufferedOutputStream(conn.getOutputStream()); long bufferSize = Math.min(fileSize, maxBufferSize); if (GPLog.LOG) GPLog.addLogEntry(TAG, "BUFFER USED: " + bufferSize); byte[] buffer = new byte[(int) bufferSize]; int bytesRead = fis.read(buffer, 0, (int) bufferSize); long totalBytesWritten = 0; while (bytesRead > 0) { wr.write(buffer, 0, (int) bufferSize); totalBytesWritten = totalBytesWritten + bufferSize; if (totalBytesWritten >= fileSize) break; bufferSize = Math.min(fileSize - totalBytesWritten, maxBufferSize); bytesRead = fis.read(buffer, 0, (int) bufferSize); } wr.flush(); String responseMessage = conn.getResponseMessage(); if (GPLog.LOG) GPLog.addLogEntry(TAG, "POST RESPONSE: " + responseMessage); return responseMessage; } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (wr != null) wr.close(); if (fis != null) fis.close(); if (conn != null) conn.disconnect(); } }