List of usage examples for java.net HttpURLConnection setChunkedStreamingMode
public void setChunkedStreamingMode(int chunklen)
From source file:stroom.util.ErrorDataFeedClient.java
public static void main(final String[] args) { try {// ww w. ja va 2s . c o m final HashMap<String, String> argsMap = new HashMap<String, String>(); for (int i = 0; i < args.length; i++) { final String[] split = args[i].split("="); if (split.length > 1) { argsMap.put(split[0], split[1]); } else { argsMap.put(split[0], ""); } } final String urlS = argsMap.get(ARG_URL); final long startTime = System.currentTimeMillis(); final URL url = new URL(urlS); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier((arg0, arg1) -> { System.out.println("HostnameVerifier - " + arg0); return true; }); } connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/audit"); connection.setDoOutput(true); connection.setDoInput(true); // Also add all our command options for (final Entry<String, String> entry : argsMap.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } final int bufferSize = argsMap.containsKey(BUFFER_SIZE) ? Integer.parseInt(argsMap.get(BUFFER_SIZE)) : 100; final int chunkSize = argsMap.containsKey(CHUNK_SIZE) ? Integer.parseInt(argsMap.get(CHUNK_SIZE)) : 100; final int writeSize = argsMap.containsKey(WRITE_SIZE) ? Integer.parseInt(argsMap.get(WRITE_SIZE)) : 1000; connection.setChunkedStreamingMode(chunkSize); connection.connect(); OutputStream out = connection.getOutputStream(); // Using Zip Compression we just have 1 file (called 1) if (ZIP.equalsIgnoreCase(argsMap.get(ARG_COMPRESSION))) { final ZipOutputStream zout = new ZipOutputStream(out); zout.putNextEntry(new ZipEntry("1")); out = zout; System.out.println("Using ZIP"); } if (GZIP.equalsIgnoreCase(argsMap.get(ARG_COMPRESSION))) { out = new GZIPOutputStream(out); System.out.println("Using GZIP"); } // Write the output final byte[] buffer = buildDataBuffer(bufferSize); int writtenSize = 0; while (writtenSize < writeSize) { out.write(buffer, 0, bufferSize); out.flush(); writtenSize += bufferSize; } if (writtenSize >= writeSize) { throw new IOException("Test Error"); } out.close(); final int response = connection.getResponseCode(); final String msg = connection.getResponseMessage(); connection.disconnect(); System.out.println( "Client Got Response " + response + " in " + (System.currentTimeMillis() - startTime) + "ms"); if (msg != null && msg.length() > 0) { System.out.println(msg); } } catch (final Exception ex) { ex.printStackTrace(); } }
From source file:Main.java
public static HttpURLConnection openUrlConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setUseCaches(false);//from w ww. j av a 2 s .c o m conn.setChunkedStreamingMode(0); conn.setRequestProperty("User-Agent", USER_AGENT); conn.connect(); return conn; }
From source file:com.avinashbehera.sabera.network.HttpClient.java
public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) { URL sendUrl;/* w w w . jav a2 s . c om*/ try { sendUrl = new URL(url); } catch (MalformedURLException e) { Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL"); return null; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) sendUrl.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setChunkedStreamingMode(1024); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + ""); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); //writer.write(getPostDataStringfromJsonObject(jsonObjSend)); Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString()); //writer.write(jsonObjSend.toString()); writer.write(String.valueOf(jsonObjSend)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); Log.d(TAG, "responseCode = " + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { Log.d(TAG, "responseCode = HTTP OK"); InputStream instream = conn.getInputStream(); String resultString = convertStreamToString(instream); instream.close(); Log.d(TAG, "resultString = " + resultString); //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONParser parser = new JSONParser(); JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; }
From source file:circleplus.app.http.AbstractHttpApi.java
private static HttpURLConnection getHttpURLConnection(URL url, int requestMethod, boolean acceptJson) throws IOException { if (D)/*from w w w. j a v a 2 s . c om*/ Log.d(TAG, "execute method: " + requestMethod + " url: " + url.toString() + " accept JSON ?= " + acceptJson); String method; boolean isPost; switch (requestMethod) { case REQUEST_METHOD_GET: method = "GET"; isPost = false; break; case REQUEST_METHOD_POST: method = "POST"; isPost = true; break; default: method = "GET"; isPost = false; break; } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT); conn.setConnectTimeout(TIMEOUT); conn.setRequestProperty("Content-Type", JSON_UTF8_CONTENT_TYPE); if (isPost && acceptJson) { conn.setRequestProperty("Accept", JSON_CONTENT_TYPE); } conn.setRequestMethod(method); /* setDoOutput(true) equals setRequestMethod("POST") */ conn.setDoOutput(isPost); conn.setChunkedStreamingMode(0); // Starts the query conn.connect(); return conn; }
From source file:net.mceoin.cominghome.api.NestUtil.java
/** * Make HTTP/JSON call to Nest and set away status. * * @param access_token OAuth token to allow access to Nest * @param structure_id ID of structure with thermostat * @param away_status Either "home" or "away" * @return Equal to "Success" if successful, otherwise it contains a hint on the error. *///from w ww . j a va2s. com public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) { String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try { URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); String payload = "\"" + away_status + "\""; OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); log.info(payload); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); urlConnection.setRequestProperty("Accept", "application/json"); // System.out.println("Redirect to URL : " + newUrl); wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) { return "Error: " + errorResult; } else { return "Success"; } }
From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.java
/** * <pre>//from ww w .j av a 2s. c o m * Add a multipart and write it to output of a connection. * * NOTE : It only supports chunked transfer encoding mode, * the server should supports it. * </pre> */ private static void addMultipartIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { OutputStream os = null; try { if (!(request instanceof MultipartContainer)) { return; } MultipartContainer container = (MultipartContainer) request; if (!container.hasMultipart()) { return; } Multipart multipart = container.getMultipart(); if (multipart == null) { return; } connection.setDoOutput(true); connection.addRequestProperty("Content-Type", multipart.getContentType()); // Set chunked encoding mode. connection.setChunkedStreamingMode(DEFAULT_CHUNK_LENGTH); os = connection.getOutputStream(); multipart.write(os); os.flush(); } finally { if (os != null) { os.close(); } } }
From source file:rst.sample.mtom.client.ws.ChunkedEncodingMessageSender.java
@Override protected void prepareConnection(final HttpURLConnection connection) throws IOException { super.prepareConnection(connection); connection.setChunkedStreamingMode(-1); }
From source file:org.sample.nonblocking.TestClient.java
/** * Processes requests for both HTTP// w w w .j a v a2 s .c o 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:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
public static boolean logout(String server_url) { if (isEmpty(server_url)) { Logd(TAG, "revokSite no server url"); return false; }/*from www . j a v a2s . c o m*/ if (!server_url.endsWith("/")) server_url += "/"; // get end session endpoint String end_session_endpoint = getEndpointFromConfigOidc("end_session_endpoint", server_url); if (isEmpty(end_session_endpoint)) { Logd(TAG, "logout : could not get end_session_endpoint on server : " + server_url); return false; } // set up connection HttpURLConnection huc = getHUC(end_session_endpoint); // TAZTAG test // huc.setInstanceFollowRedirects(false); huc.setInstanceFollowRedirects(true); // result : follows redirection is ok for taztag huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); // prepare parameters List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); try { // write parameters to http connection OutputStream os = huc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // get URL encoded string from list of key value pairs String postParam = getQuery(nameValuePairs); Logd("Logout", "url: " + end_session_endpoint); Logd("Logout", "POST: " + postParam); writer.write(postParam); writer.flush(); writer.close(); os.close(); // try to connect huc.connect(); // connexion status int responseCode = huc.getResponseCode(); Logd(TAG, "Logout response: " + responseCode); // if 200 - OK if (responseCode == 200) { return true; } huc.disconnect(); } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:org.smartfrog.services.www.bulkio.client.AbstractBulkIOClient.java
/** * Set chunking. <i>DO NOT DO THIS ON A GET AS the JDK CANNOT HANDLE IT</i> * * @param connection/*from w w w . ja v a2s . c om*/ */ protected void maybeSetChunking(HttpURLConnection connection) { if (chunked) { connection.setChunkedStreamingMode(chunkLength); } }