List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.hollandhaptics.babyapp.BabyService.java
/** * @param sourceFile The file to upload. * @return int The server's response code. * @brief Uploads a file to the server. Is called by uploadAudioFiles(). *///from w ww. j a va 2 s.c o m public int uploadFile(File sourceFile) { HttpURLConnection conn; DataOutputStream dos; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1024 * 1024; String sourceFileUri = sourceFile.getAbsolutePath(); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File does not exist :" + sourceFileUri); return 0; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("fileToUpload", sourceFileUri); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\"" + sourceFileUri + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { boolean deleted = sourceFile.delete(); Log.i("Deleted succes", String.valueOf(deleted)); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server", "Exception : " + e.getMessage(), e); } return serverResponseCode; } // End else block }
From source file:fur.shadowdrake.minecraft.InstallPanel.java
public boolean downloadMojangLauncher() { URL u;/* w w w. j a v a 2s. c o m*/ HttpURLConnection connection; Proxy p; InputStream is; FileOutputStream fos; if (new File(config.getInstallDir(), "Minecraft.jar").isFile()) { return true; } log.println("Connecting to Mojang server..."); if (config.getHttpProxy().isEmpty()) { p = Proxy.NO_PROXY; } else { Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == Authenticator.RequestorType.PROXY) { return config.getHttpProxyCredentials(); } else { return super.getPasswordAuthentication(); } } }); p = new Proxy(Proxy.Type.HTTP, new ProxyAddress(config.getHttpProxy(), 3128).getSockaddr()); } try { u = new URL("https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar"); connection = (HttpURLConnection) u.openConnection(p); connection.addRequestProperty("User-agent", "Minecraft Bootloader"); connection.setUseCaches(false); connection.setDefaultUseCaches(false); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.connect(); log.println("Mojang server returned " + connection.getResponseMessage()); if (connection.getResponseCode() != 200) { connection.disconnect(); return false; } } catch (MalformedURLException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex); log.println("Connection to Mojang server failed."); return false; } try { is = connection.getInputStream(); fos = new FileOutputStream(new File(config.getInstallDir(), "Minecraft.jar")); log.println("Downloading Minecraft.jar"); byte[] buffer = new byte[4096]; for (int n = is.read(buffer); n > 0; n = is.read(buffer)) { fos.write(buffer, 0, n); } fos.close(); is.close(); connection.disconnect(); log.println("Done."); } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "downloadMojangLauncher", ex); log.println("Faild to save file."); return false; } return true; }
From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java
private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status) throws IOException { AQUtility.debug("multipart", url); HttpURLConnection conn = null; DataOutputStream dos = null;/*from w w w. jav a2 s. c o m*/ URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(NET_TIMEOUT * 4); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary); if (headers != null) { for (String name : headers.keySet()) { conn.setRequestProperty(name, headers.get(name)); } } String cookie = makeCookie(); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } if (ah != null) { ah.applyToken(this, conn); } dos = new DataOutputStream(conn.getOutputStream()); Object o = null; if (progress != null) { o = progress.get(); } Progress p = null; if (o != null) { p = new Progress(o); } for (Map.Entry<String, Object> entry : params.entrySet()) { writeObject(dos, entry.getKey(), entry.getValue(), p); } dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); conn.connect(); int code = conn.getResponseCode(); String message = conn.getResponseMessage(); byte[] data = null; String encoding = conn.getContentEncoding(); String error = null; if ((code < 200) || (code >= 300)) { error = new String(toData(encoding, conn.getErrorStream()), "UTF-8"); AQUtility.debug("error", error); } else { data = toData(encoding, conn.getInputStream()); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null); }
From source file:ManagerQuery.java
private void notifyEvent(double valueNum, Rule rule) { Properties conf2 = new Properties(); try {//www. j ava2 s. c om FileInputStream in = new FileInputStream("./config.properties"); conf2.load(in); in.close(); } catch (FileNotFoundException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } String url = conf2.getProperty("notificatorRestInterfaceUrl"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String apiUsr = conf2.getProperty("notificatorRestInterfaceUsr"); String apiPwd = conf2.getProperty("notificatorRestInterfacePwd"); String operation = "notifyEvent"; String generatorOriginalName = rule.getWidgetTitle(); String generatorOriginalType = rule.getMetricName(); String containerName = rule.getDashboardTitle(); String eventType = rule.getEventType(); String value = Double.toString(valueNum); Calendar date = new GregorianCalendar(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String eventTime = sdf.format(date.getTime()); String appName = "Dashboard Manager"; String params = null; URL obj = null; HttpURLConnection con = null; try { obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Charset", charset); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); params = String.format( "apiUsr=%s&apiPwd=%s&appName=%s&operation=%s&generatorOriginalName=%s&generatorOriginalType=%s&containerName=%s&eventType=%s&eventTime=%s&value=%s", URLEncoder.encode(apiUsr, charset), URLEncoder.encode(apiPwd, charset), URLEncoder.encode(appName, charset), URLEncoder.encode(operation, charset), URLEncoder.encode(generatorOriginalName, charset), URLEncoder.encode(generatorOriginalType, charset), URLEncoder.encode(containerName, charset), URLEncoder.encode(eventType, charset), URLEncoder.encode(eventTime, charset), URLEncoder.encode(value, charset)); } catch (MalformedURLException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } // Questo rende la chiamata una POST con.setDoOutput(true); DataOutputStream wr = null; try { wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); String responseMessage = con.getResponseMessage(); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ManagerQuery.java
private void notifyEvent(String eventType, String furtherDetails) { Properties conf2 = new Properties(); try {// w ww .j av a 2 s . c o m FileInputStream in = new FileInputStream("./config.properties"); conf2.load(in); in.close(); } catch (FileNotFoundException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } String url = conf2.getProperty("notificatorRestInterfaceUrl"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String apiUsr = conf2.getProperty("notificatorRestInterfaceUsr"); String apiPwd = conf2.getProperty("notificatorRestInterfacePwd"); String operation = "notifyEvent"; String generatorOriginalName = this.idProc; String generatorOriginalType = this.metricType; String containerName = this.dataSourceId; Calendar date = new GregorianCalendar(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String eventTime = sdf.format(date.getTime()); String appName = "Dashboard Data Process"; String params = null; URL obj = null; HttpURLConnection con = null; try { obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Charset", charset); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); params = String.format( "apiUsr=%s&apiPwd=%s&appName=%s&operation=%s&generatorOriginalName=%s&generatorOriginalType=%s&containerName=%s&eventType=%s&eventTime=%s&furtherDetails=%s", URLEncoder.encode(apiUsr, charset), URLEncoder.encode(apiPwd, charset), URLEncoder.encode(appName, charset), URLEncoder.encode(operation, charset), URLEncoder.encode(generatorOriginalName, charset), URLEncoder.encode(generatorOriginalType, charset), URLEncoder.encode(containerName, charset), URLEncoder.encode(eventType, charset), URLEncoder.encode(eventTime, charset), URLEncoder.encode(furtherDetails, charset)); } catch (MalformedURLException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } // Questo rende la chiamata una POST con.setDoOutput(true); DataOutputStream wr = null; try { wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); String responseMessage = con.getResponseMessage(); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java
/** * fetch data from a given url.//w w w.j a v a 2 s .co m * * @param url * @return byte[] * @throws SourceNotAvailableException * @throws RuntimeException * @throws AccessException */ public byte[] fetchMetadatafromURL(URL url) throws SourceNotAvailableException, RuntimeException, AccessException { byte[] input = null; URLConnection conn = null; Date retryAfter = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); try { conn = ProxyHelper.openConnection(url); HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 503: String retryAfterHeader = conn.getHeaderField("Retry-After"); if (retryAfterHeader != null) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); retryAfter = dateFormat.parse(retryAfterHeader); this.logger.debug("Source responded with 503, retry after " + retryAfter + "."); throw new SourceNotAvailableException(retryAfter); } break; case 302: String alternativeLocation = conn.getHeaderField("Location"); return fetchMetadatafromURL(new URL(alternativeLocation)); case 200: this.logger.info("Source responded with 200."); // Fetch file GetMethod method = new GetMethod(url.toString()); HttpClient client = new HttpClient(); ProxyHelper.executeMethod(client, method); input = method.getResponseBody(); httpConn.disconnect(); // Create zip file with fetched file ZipEntry ze = new ZipEntry("unapi"); ze.setSize(input.length); ze.setTime(this.currentDate()); CRC32 crc321 = new CRC32(); crc321.update(input); ze.setCrc(crc321.getValue()); zos.putNextEntry(ze); zos.write(input); zos.flush(); zos.closeEntry(); zos.close(); this.setContentType("application/zip"); this.setFileEnding(".zip"); break; case 403: throw new AccessException("Access to url " + url + " is restricted."); default: throw new RuntimeException("An error occurred during importing from external system: " + responseCode + ": " + httpConn.getResponseMessage() + "."); } } catch (AccessException e) { this.logger.error("Access denied.", e); throw new AccessException(url.toString()); } catch (Exception e) { throw new RuntimeException(e); } return baos.toByteArray(); }
From source file:com.wadpam.guja.oauth2.social.NetworkTemplate.java
public <J> NetworkResponse<J> exchangeForResponse(String method, String url, Map<String, String> requestHeaders, Object requestBody, Class<J> responseClass, boolean followRedirects) { // so that we can read in case of Exception InputStream in = null;/*from w w w .j av a 2s . c o m*/ try { // expand url? if (null != requestBody && !CONTENT_METHODS.contains(method)) { Map<String, Object> paramMap = requestBody instanceof Map ? (Map) requestBody : MAPPER.convertValue(requestBody, Map.class); url = expandUrl(url, paramMap); } // create the connection URL u = new URL(url); HttpURLConnection con = (HttpURLConnection) u.openConnection(); con.setInstanceFollowRedirects(followRedirects); // override default method if (null != method) { con.setRequestMethod(method); } LOG.info("{} {}", method, url); // Accept if (null != accept) { con.addRequestProperty(ACCEPT, accept); LOG.trace("{}: {}", ACCEPT, accept); } // Authorization if (null != authorization) { con.addRequestProperty(AUTHORIZATION, authorization); LOG.trace("{}: {}", AUTHORIZATION, authorization); } // other request headers: String contentType = null; if (null != requestHeaders) { for (Entry<String, String> entry : requestHeaders.entrySet()) { con.addRequestProperty(entry.getKey(), entry.getValue()); LOG.info("{}: {}", entry.getKey(), entry.getValue()); if (CONTENT_TYPE.equalsIgnoreCase(entry.getKey())) { contentType = entry.getValue(); } } } if (null != requestBody) { if (CONTENT_METHODS.contains(method)) { // content-type not specified in request headers? if (null == contentType) { contentType = MIME_JSON; con.addRequestProperty(CONTENT_TYPE, MIME_JSON); } con.setDoOutput(true); OutputStream out = con.getOutputStream(); if (MIME_JSON.equals(contentType)) { MAPPER.writeValue(out, requestBody); final String json = MAPPER.writeValueAsString(requestBody); LOG.debug("json Content: {}", json); } else { // application/www-form-urlencoded PrintWriter writer = new PrintWriter(out); if (requestBody instanceof String) { writer.print(requestBody); LOG.debug("Content: {}", requestBody); } else { Map<String, Object> params = MAPPER.convertValue(requestBody, Map.class); String content = expandUrl("", params); writer.print(content.substring(1)); LOG.debug("Content: {}", content.substring(1)); } writer.flush(); } out.close(); } } NetworkResponse<J> response = new NetworkResponse<J>(con.getResponseCode(), con.getHeaderFields(), con.getResponseMessage()); LOG.info("HTTP {} {}", response.getCode(), response.getMessage()); // response content to read and parse? if (null != con.getContentType()) { final String responseType = con.getContentType(); LOG.debug("Content-Type: {}", responseType); in = con.getInputStream(); if (con.getContentType().startsWith(MIME_JSON)) { response.setBody(MAPPER.readValue(in, responseClass)); LOG.debug("Response JSON: {}", response.getBody()); } else if (String.class.equals(responseClass)) { String s = readResponseAsString(in, responseType); LOG.info("Read {} bytes from {}", s.length(), con.getContentType()); response.setBody((J) s); } else if (400 <= response.getCode()) { String s = readResponseAsString(in, responseType); LOG.warn(s); } in.close(); } return response; } catch (IOException ioe) { if (null != in) { try { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; while (null != (s = br.readLine())) { LOG.warn(s); } } catch (IOException ignore) { } } throw new RuntimeException(String.format("NetworkTemplate.exchange: %s", ioe.getMessage()), ioe); } }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
private ResumeInfo resumeFileUpload(String uploadUrl) throws IOException, ParserConfigurationException, SAXException, Internal500ResumeException { HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestProperty("Content-Range", "bytes */*"); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); urlConnection.setFixedLengthStreamingMode(0); HttpURLConnection.setFollowRedirects(false); urlConnection.connect();/*from w ww .j a v a 2 s .com*/ int responseCode = urlConnection.getResponseCode(); if (responseCode >= 300 && responseCode < 400) { int nextByteToUpload; String range = urlConnection.getHeaderField("Range"); if (range == null) { Log.d(TAG, String.format("PUT to %s did not return 'Range' header.", uploadUrl)); nextByteToUpload = 0; } else { Log.d(TAG, String.format("Range header is '%s'.", range)); String[] parts = range.split("-"); if (parts.length > 1) { nextByteToUpload = Integer.parseInt(parts[1]) + 1; } else { nextByteToUpload = 0; } } return new ResumeInfo(nextByteToUpload); } else if (responseCode >= 200 && responseCode < 300) { return new ResumeInfo(parseVideoId(urlConnection.getInputStream())); } else if (responseCode == 500) { // TODO this is a workaround for current problems with resuming // uploads while switching transport (Wifi->EDGE) throw new Internal500ResumeException( String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } else { throw new IOException(String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } }
From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java
private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status) throws IOException { AQUtility.debug("multipart", url); HttpURLConnection conn = null; DataOutputStream dos = null;/*from w w w. ja v a 2 s. com*/ URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(NET_TIMEOUT * 4); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary); if (headers != null) { for (String name : headers.keySet()) { conn.setRequestProperty(name, headers.get(name)); } } String cookie = makeCookie(); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } if (ah != null) { ah.applyToken(this, conn); } dos = new DataOutputStream(conn.getOutputStream()); for (Map.Entry<String, Object> entry : params.entrySet()) { writeObject(dos, entry.getKey(), entry.getValue()); } dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); conn.connect(); int code = conn.getResponseCode(); String message = conn.getResponseMessage(); byte[] data = null; String encoding = conn.getContentEncoding(); String error = null; if (code < 200 || code >= 300) { error = new String(toData(encoding, conn.getErrorStream()), "UTF-8"); AQUtility.debug("error", error); } else { data = toData(encoding, conn.getInputStream()); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null); }
From source file:org.apache.openaz.xacml.pdp.test.TestBase.java
/** * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. * * @param file/*from w w w . java2s . c o m*/ * @return */ protected Response callRESTfulPDP(InputStream is) { Response response = null; HttpURLConnection connection = null; try { // // Open up the connection // connection = (HttpURLConnection) this.restURL.openConnection(); connection.setRequestProperty("Content-Type", "application/json"); // // Setup our method and headers // connection.setRequestMethod("POST"); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); // // Send the request // try (OutputStream os = connection.getOutputStream()) { IOUtils.copy(is, os); } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 200) { // // Read the response // ContentType contentType = null; try { contentType = ContentType.parse(connection.getContentType()); if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { response = JSONResponse.load(connection.getInputStream()); } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { response = DOMResponse.load(connection.getInputStream()); } else { logger.error("unknown content-type: " + contentType); } } catch (Exception e) { String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); logger.error(message, e); } } else { logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (Exception e) { logger.error(e); } return response; }