List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.parasoft.em.client.impl.JSONClient.java
private HttpURLConnection getConnection(String restPath) throws IOException { URL url = new URL(baseUrl + restPath); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept", "application/json"); if (username != null) { String encoding = username + ":" + password; encoding = Base64.encodeBase64String(encoding.getBytes("UTF-8")); connection.setRequestProperty("Authorization", "Basic " + encoding); }/*from w w w. j av a 2 s . c o m*/ return connection; }
From source file:io.ericwittmann.corsproxy.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from ww w . ja va 2 s . co m @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:br.bireme.tb.URLS.java
/** * Given an url, loads its content (POST - method) * @param url url to be loaded//ww w . jav a2 s .c o m * @param urlParameters post parameters * @return an array with the real location of the page (in case of redirect) * and its content. * @throws IOException */ public static String[] loadPagePost(final URL url, final String urlParameters) throws IOException { if (url == null) { throw new NullPointerException("url"); } if (urlParameters == null) { throw new NullPointerException("urlParameters"); } final String encodedParams = URLEncoder.encode(urlParameters, DEFAULT_ENCODING); //System.out.print("loading page (POST): [" + url + "] params: " + urlParameters); //Create connection final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(encodedParams.getBytes().length)); //.getBytes(DEFAULT_ENCODING).length)); connection.setRequestProperty("Content-Language", "pt-BR"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(encodedParams.getBytes(DEFAULT_ENCODING)); //wr.writeBytes(urlParameters); wr.flush(); } //Get Response final StringBuffer response = new StringBuffer(); try (final BufferedReader rd = new BufferedReader( new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING))) { while (true) { final String line = rd.readLine(); if (line == null) { break; } response.append(line); response.append('\n'); } } connection.disconnect(); return new String[] { url.toString() + "?" + urlParameters, response.toString() }; }
From source file:de.zib.scalaris.examples.wikipedia.plugin.fourcaast.FourCaastAccounting.java
protected void pushSdrToServer(final WikiPageBeanBase page) { if (!page.getServiceUser().isEmpty()) { final String sdr = createSdr(page); // System.out.println("Sending sdr...\n" + sdr); try {// w ww. j av a2 s.com HttpURLConnection urlConn = (HttpURLConnection) accountingServer.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream()); out.write(sdr); out.close(); //read the result from the server (necessary for the request to be send!) BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) != null) { sb.append(line + '\n'); } // System.out.println(sb.toString()); in.close(); } catch (ProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.threewks.analytics.client.AnalyticsClient.java
/** * Post JSON a URL. Ignore (but log) any errors. * /* ww w .ja v a 2s .c o m*/ * @param url the URL to post the data to. * @param json the JSON data to post. */ void postJson(String url, String json) { PrintWriter writer = null; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setDoOutput(true); connection.setRequestProperty(API_KEY_HEADER, apiKey); connection.setRequestProperty(CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE); writer = new PrintWriter(connection.getOutputStream(), true); writer.append(json); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode != 200) { logger.warning(String.format( "Analytics server returned HTTP response code: %s when posting data to url: %s", responseCode, url)); } } catch (Exception e) { logger.warning(String.format("Error sending data to url: %s, error: %s", url, e.getMessage())); } finally { IOUtils.closeQuietly(writer); } }
From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { VolleyLog.e("======setConnectionParametersForRequest:"); switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards // compatibility. // If the request's post body is null, then the assumption is that // the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length // explicitly, // since this is handled by HttpURLConnection using the size of // the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/*from w w w . j a v a2 s . c o m*/ out.close(); } break; case Method.GET: // Not necessary to set the request method because connection // defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; case Method.HEAD: connection.setRequestMethod("HEAD"); break; case Method.OPTIONS: connection.setRequestMethod("OPTIONS"); break; case Method.TRACE: connection.setRequestMethod("TRACE"); break; case Method.PATCH: connection.setRequestMethod("PATCH"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:to.noc.devicefp.server.service.MaxMindServiceImpl.java
private MaxMindLocation createFromWebService(String ip) { MaxMindLocation location = null;/*from ww w . j a v a 2s . c o m*/ try { URL url = new URL("http://geoip.maxmind.com/e?l=" + maxMindLicenseKey + "&i=" + ip); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setConnectTimeout(10 * 1000); // 10 seconds BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream(), "ISO-8859-1")); String resultsLine = r.readLine(); connection.disconnect(); if (resultsLine != null) { // Split on a comma only if it has zero or an even number of quotes // after it. Assumes quotes are never escaped. String values[] = resultsLine.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); location = new MaxMindLocation(); location.setIpAddress(ip); location.setStamp(new Date()); for (GeoIpField field : GeoIpField.values()) { if (field.ordinal() >= values.length) { break; } String val = values[field.ordinal()]; // replace leading and trailing whitespace and quotes val = val.replaceAll("^\"?\\s*|\\s*\"?$", ""); if (!val.isEmpty()) { addLocationField(location, field, val); } } } } catch (Exception ex) { log.error("", ex); location = null; } return location; }
From source file:ai.api.RequestTask.java
@Override protected String doInBackground(final String... params) { final String payload = params[0]; if (TextUtils.isEmpty(payload)) { throw new IllegalArgumentException("payload argument should not be empty"); }//from ww w. j a v a 2s . c o m String response = null; HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.connect(); final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.write(payload, outputStream, Charsets.UTF_8); outputStream.close(); final InputStream inputStream = new BufferedInputStream(connection.getInputStream()); response = IOUtils.toString(inputStream, Charsets.UTF_8); inputStream.close(); return response; } catch (final IOException e) { Log.e(TAG, "Can't make request to the Speaktoit AI service. Please, check connection settings and API access token.", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:org.sample.nonblocking.TestClient.java
/** * Processes requests for both HTTP/*from w w w .jav a 2 s .co m*/ * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestClient</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet TestClient at " + request.getContextPath() + "</h1>"); String path = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/ReadTestServlet"; out.println("Invoking the endpoint: " + path + "<br>"); out.flush(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setChunkedStreamingMode(2); conn.setDoOutput(true); conn.connect(); try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()))) { out.println("Sending data ..." + "<br>"); out.flush(); output.write("Hello"); output.flush(); out.println("Sleeping ..." + "<br>"); out.flush(); Thread.sleep(5000); out.println("Sending more data ..." + "<br>"); out.flush(); output.write("World"); output.flush(); output.close(); } out.println("<br><br>Check GlassFish server.log"); out.println("</body>"); out.println("</html>"); } catch (InterruptedException | IOException ex) { Logger.getLogger(ReadTestServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:cloudlens.engine.CL.java
public Object post(String urlString, String jsonData) throws IOException { final URL url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true);/*from www .j av a 2 s . c om*/ final Matcher matcher = Pattern.compile("//([^@]+)@").matcher(urlString); if (matcher.find()) { final String encoding = Base64.getEncoder().encodeToString(matcher.group(1).getBytes()); conn.setRequestProperty("Authorization", "Basic " + encoding); } conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestMethod("POST"); try (final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) { wr.write(jsonData); wr.flush(); } try (final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; final StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } final String s = StringEscapeUtils.escapeEcmaScript(sb.toString()); final Object log = engine.eval( "CL.log=JSON.parse(\"" + s + "\").hits.hits.map(function (entry) { return entry._source})"); return log; } }