List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:io.ericwittmann.corsproxy.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from www . j av a 2s. com*/ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = "https://issues.jboss.org" + req.getPathInfo(); if (req.getQueryString() != null) { url += "?" + req.getQueryString(); } System.out.println("Proxying to: " + url); boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put"); URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); if (isWrite) { remoteConn.setDoOutput(true); } String auth = req.getHeader("Authorization"); if (auth != null) { remoteConn.setRequestProperty("Authorization", auth); } if (isWrite) { InputStream requestIS = null; OutputStream remoteOS = null; try { requestIS = req.getInputStream(); remoteOS = remoteConn.getOutputStream(); IOUtils.copy(requestIS, remoteOS); remoteOS.flush(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); return; } finally { IOUtils.closeQuietly(requestIS); IOUtils.closeQuietly(remoteOS); } } InputStream remoteIS = null; OutputStream responseOS = null; try { Map<String, List<String>> headerFields = remoteConn.getHeaderFields(); for (String headerName : headerFields.keySet()) { if (headerName == null) { continue; } if (EXCLUDE_HEADERS.contains(headerName)) { continue; } String headerValue = remoteConn.getHeaderField(headerName); resp.setHeader(headerName, headerValue); } resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); IOUtils.copy(remoteIS, responseOS); resp.flushBuffer(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } }
From source file:com.commsen.jwebthumb.WebThumbService.java
private HttpURLConnection getFetchConnection(WebThumbFetchRequest webThumbFetchRequest) throws WebThumbException { Validate.notNull(webThumbFetchRequest, "webThumbFetchRequest is null!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Attempting to send webThumbFetchRequest: " + webThumbFetchRequest); }/*from w w w. java 2 s .com*/ WebThumb webThumb = new WebThumb(apikey, webThumbFetchRequest); try { HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setRequestMethod("POST"); SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream()); int responseCode = connection.getResponseCode(); String contentType = getContentType(connection); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("webThumbFetchRequest sent. Got response: " + responseCode + " " + connection.getResponseMessage()); LOGGER.fine("Content type: " + contentType); } if (responseCode == HttpURLConnection.HTTP_OK) { if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) { throw new WebThumbException( "Server side error: " + IOUtils.toString(connection.getInputStream())); } return connection; } else if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { WebThumbResponse webThumbResponse = SimpleXmlSerializer.parseResponse(connection.getErrorStream(), WebThumbResponse.class); throw new WebThumbException("Server side error: " + webThumbResponse.getError().getValue()); } else { throw new WebThumbException("Server side error: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (MalformedURLException e) { throw new WebThumbException("failed to send request", e); } catch (IOException e) { throw new WebThumbException("failed to send request", e); } }
From source file:com.vimc.ahttp.HurlWorker.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void addBodyIfExists(HttpURLConnection connection, Request request) throws IOException { if (request.containsMutilpartData()) { connection.setDoOutput(true);/* w w w. ja va2 s. c o m*/ connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (request.getStringParams().size() > 0) { writeStringFields(request.getStringParams(), out, request.getBoundray()); } if (request.getFileParams().size() > 0) { writeFiles(request.getFileParams(), out, request.getBoundray()); } if (request.getByteParams().size() > 0) { writeBytes(request.getByteParams(), out, request.getBoundray()); } out.flush(); out.close(); } else { byte[] body = request.getStringBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.flush(); out.close(); } } }
From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java
/** * Append to an existing file (optional operation). * <p/>//from w ww. ja v a2 s . c o m * IMPORTANT: The <code>Progressable</code> parameter is not used. * * @param f the existing file to be appended. * @param bufferSize the size of the buffer to be used. * @param progress for reporting progress if it is not null. * @throws IOException */ @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { Map<String, String> params = new HashMap<String, String>(); params.put("op", "append"); HttpURLConnection conn = getConnection("PUT", params, f); try { OutputStream os = new BufferedOutputStream(conn.getOutputStream(), bufferSize); return new HoopFSDataOutputStream(conn, os, HttpURLConnection.HTTP_OK, statistics); } catch (IOException ex) { validateResponse(conn, HttpURLConnection.HTTP_OK); throw ex; } }
From source file:nl.b3p.viewer.stripes.ProxyActionBean.java
private Resolution proxyArcIMS() throws Exception { HttpServletRequest request = getContext().getRequest(); if (!"POST".equals(request.getMethod())) { return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN); }//w w w. ja v a2 s .c o m Map params = new HashMap(getContext().getRequest().getParameterMap()); // Only allow these parameters in proxy request params.keySet().retainAll(Arrays.asList("ClientVersion", "Encode", "Form", "ServiceName")); URL theUrl = new URL(url); // Must not allow file / jar etc protocols, only HTTP: String path = theUrl.getPath(); for (Map.Entry<String, String[]> param : (Set<Map.Entry<String, String[]>>) params.entrySet()) { if (path.length() == theUrl.getPath().length()) { path += "?"; } else { path += "&"; } path += URLEncoder.encode(param.getKey(), "UTF-8") + "=" + URLEncoder.encode(param.getValue()[0], "UTF-8"); } theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path); // TODO logging for inspecting malicious proxy use ByteArrayOutputStream post = new ByteArrayOutputStream(); IOUtils.copy(request.getInputStream(), post); // This check makes some assumptions on how browsers serialize XML // created by OpenLayers' ArcXML.js write() function (whitespace etc.), // but all major browsers pass this check if (!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) { return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN); } final HttpURLConnection connection = (HttpURLConnection) theUrl.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setAllowUserInteraction(false); connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr()); connection.connect(); try { IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream()); } finally { connection.getOutputStream().flush(); connection.getOutputStream().close(); } return new StreamingResolution(connection.getContentType()) { @Override protected void stream(HttpServletResponse response) throws IOException { try { IOUtils.copy(connection.getInputStream(), response.getOutputStream()); } finally { connection.disconnect(); } } }; }
From source file:com.streamsets.datacollector.updatechecker.UpdateChecker.java
@Override public void run() { updateInfo = null;//from w w w .j a va 2 s. c o m PipelineState ps; try { ps = runner.getState(); } catch (PipelineStoreException e) { LOG.warn(Utils.format("Cannot get pipeline state: '{}'", e.toString()), e); return; } if (ps.getStatus() == PipelineStatus.RUNNING) { if (url != null) { Map uploadInfo = getUploadInfo(); if (uploadInfo != null) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(2000); conn.setReadTimeout(2000); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("content-type", APPLICATION_JSON_MIME); ObjectMapperFactory.getOneLine().writeValue(conn.getOutputStream(), uploadInfo); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { String responseContentType = conn.getHeaderField("content-type"); if (APPLICATION_JSON_MIME.equals(responseContentType)) { updateInfo = ObjectMapperFactory.get().readValue(conn.getInputStream(), Map.class); } else { LOG.trace("Got invalid content-type '{}' from from update-check server", responseContentType); } } else { LOG.trace("Got '{} : {}' from update-check server", conn.getResponseCode(), conn.getResponseMessage()); } } catch (Exception ex) { LOG.trace("Could not do an update check: {}", ex.toString(), ex); } finally { if (conn != null) { conn.disconnect(); } } } } } }
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public byte[] post(String url, byte[] data, Map<String, List<String>> headers) throws IOException { // Build and connect HttpURLConnection connection = buildConnection(url); applyHeaders(connection, headers);/*from w ww .j av a 2 s . co m*/ connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // Send the request connection.getOutputStream().write(data); connection.getOutputStream().flush(); connection.getOutputStream().close(); // Check for errors checkForErrors(connection); // Get the result return disconnectAndReturn(connection, IOUtils.toByteArray(connection.getInputStream())); }
From source file:com.sample.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /*from w w w.j a v a 2s . c om*/ * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-Util", method + " URL: " + url); //url+="&fields=email"; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setConnectTimeout(45000); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:dk.defxws.fgssolrremote.OperationsImpl.java
private StringBuffer sendToSolr(String solrCommand, String postParameters) throws Exception { if (logger.isDebugEnabled()) logger.debug("sendToSolr solrCommand=" + solrCommand + "\nPost parameters=\n" + postParameters); String base = config.getIndexBase(indexName); URI uri = new URI(base + solrCommand); URL url = uri.toURL();//w ww . jav a2s.com HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (postParameters != null) { con.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); con.setRequestMethod("POST"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); Writer writer = new OutputStreamWriter(out, "UTF-8"); Reader reader = new StringReader(postParameters); char[] buf = new char[1024]; int read = 0; while ((read = reader.read(buf)) >= 0) { writer.write(buf, 0, read); } writer.flush(); writer.close(); out.close(); } int responseCode = con.getResponseCode(); if (logger.isDebugEnabled()) logger.debug("sendToSolr solrCommand=" + solrCommand + " response Code=" + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if (logger.isDebugEnabled()) logger.debug("sendToSolr solrCommand=" + solrCommand + "\n response=" + response); return response; }
From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java
/** * Opens an FSDataOutputStream at the indicated Path with write-progress * reporting./*from ww w. j a v a2 s .co m*/ * <p/> * IMPORTANT: The <code>Progressable</code> parameter is not used. * * @param f the file name to open * @param permission * @param overwrite if a file with this name already exists, then if true, * the file will be overwritten, and if false an error will be thrown. * @param bufferSize the size of the buffer to be used. * @param replication required block replication for the file. * @param blockSize * @param progress * @throws IOException * @see #setPermission(Path, FsPermission) */ @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { Map<String, String> params = new HashMap<String, String>(); params.put("op", "create"); params.put("overwrite", Boolean.toString(overwrite)); params.put("replication", Short.toString(replication)); params.put("blocksize", Long.toString(blockSize)); params.put("permission", permissionToString(permission)); HttpURLConnection conn = getConnection("POST", params, f); try { OutputStream os = new BufferedOutputStream(conn.getOutputStream(), bufferSize); return new HoopFSDataOutputStream(conn, os, HttpURLConnection.HTTP_CREATED, statistics); } catch (IOException ex) { validateResponse(conn, HttpURLConnection.HTTP_CREATED); throw ex; } }