List of usage examples for java.net HttpURLConnection setFixedLengthStreamingMode
public void setFixedLengthStreamingMode(long contentLength)
From source file:com.nkc.nkcpost.helper.HttpRequest.java
/** * Post the request/* ww w .ja v a2 s . co m*/ * * @param url where to post to * @param requestBody the body of the request * @throws IOException */ public void doPost(String url, String requestBody) throws IOException { //Log.i(LoggingService.LOG_TAG, "HTTP request. body: " + requestBody); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(requestBody.getBytes().length); conn.setRequestMethod("POST"); for (int i = 0; i < mHeaders.size(); i++) { conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i)); } OutputStream out = null; try { out = conn.getOutputStream(); out.write(requestBody.getBytes()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore. } } } responseCode = conn.getResponseCode(); InputStream inputStream = null; try { if (responseCode == 200) { inputStream = conn.getInputStream(); } else { inputStream = conn.getErrorStream(); } responseBody = getString(inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // Ignore. } } } //Log.i(LoggingService.LOG_TAG, "HTTP response. body: " + responseBody); conn.disconnect(); }
From source file:net.bashtech.geobot.BotManager.java
public static String putRemoteData(String urlString, String postData) throws IOException { URL url;//from w w w . j av a2 s .c om HttpURLConnection conn; try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setFixedLengthStreamingMode(postData.getBytes().length); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/vnd.twitchtv.v2+json"); conn.setRequestProperty("Authorization", "OAuth " + BotManager.getInstance().krakenOAuthToken); conn.setRequestProperty("Client-ID", BotManager.getInstance().krakenClientID); // conn.setConnectTimeout(5 * 1000); // conn.setReadTimeout(5 * 1000); PrintWriter out = new PrintWriter(conn.getOutputStream()); out.print(postData); out.close(); String response = ""; Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) response += (inStream.nextLine()); return response; } catch (MalformedURLException ex) { ex.printStackTrace(); } return ""; }
From source file:net.bashtech.geobot.BotManager.java
public static String postRemoteDataTwitch(String urlString, String postData, int krakenVersion) { URL url;/* w ww. j av a 2 s . c o m*/ HttpURLConnection conn; try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setFixedLengthStreamingMode(postData.getBytes().length); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Accept", "application/vnd.twitchtv.v" + krakenVersion + "+json"); conn.setRequestProperty("Authorization", "OAuth " + BotManager.getInstance().krakenOAuthToken); conn.setRequestProperty("Client-ID", BotManager.getInstance().krakenClientID); // conn.setConnectTimeout(5 * 1000); // conn.setReadTimeout(5 * 1000); PrintWriter out = new PrintWriter(conn.getOutputStream()); out.print(postData); out.close(); String response = ""; Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) response += (inStream.nextLine()); inStream.close(); return response; } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return ""; }
From source file:com.weebly.opus1269.copyeverywhere.cloud.HttpRequest.java
/** * Post the request//from ww w . java 2 s .c o m * * @param url where to post to * @param requestBody the body of the request * @throws IOException */ public void doPost(String url, String requestBody) throws IOException { if (BuildConfig.DEBUG) { Log.i(TAG, "HTTP request. body: " + requestBody); } final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(requestBody.getBytes(UTF_8).length); conn.setRequestMethod("POST"); for (int i = 0; i < mHeaders.size(); i++) { conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i)); } OutputStream out = null; try { out = conn.getOutputStream(); out.write(requestBody.getBytes(UTF_8)); } finally { if (out != null) { try { out.close(); } catch (final IOException ignored) { // Ignore. } } } mResponseCode = conn.getResponseCode(); InputStream inputStream = null; try { if (mResponseCode == 200) { inputStream = conn.getInputStream(); } else { inputStream = conn.getErrorStream(); } mResponseBody = getString(inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (final IOException ignored) { // Ignore. } } } if (BuildConfig.DEBUG) { Log.i(TAG, "HTTP response. body: " + mResponseBody); } conn.disconnect(); }
From source file:org.jboss.aerogear.unifiedpush.message.sender.GCMForChromePushNotificationSender.java
/** * Returns HttpURLConnection that 'posts' the given body to the given URL. *///w ww . j a va2 s . c om protected HttpURLConnection post(String url, String body, String accessToken) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } byte[] bytes = body.getBytes(UTF_8); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Bearer " + accessToken); conn.setRequestMethod("POST"); OutputStream out = null; try { out = conn.getOutputStream(); out.write(bytes); } finally { // in case something blows up, while writing // the payload, we wanna close the stream: if (out != null) { out.close(); } } return conn; }
From source file:org.jboss.aerogear.unifiedpush.message.sender.GCMForChromePushNotificationSender.java
protected HttpURLConnection refreshAccessToken(ChromePackagedAppVariant chromePackagedAppVariant) throws IOException { String body = "client_secret=" + chromePackagedAppVariant.getClientSecret() + "&grant_type=refresh_token&refresh_token=" + chromePackagedAppVariant.getRefreshToken() + "&client_id=" + chromePackagedAppVariant.getClientId(); byte[] bytes = body.getBytes(UTF_8); HttpURLConnection conn = getConnection(ACCESS_TOKEN_URL); conn.setDoOutput(true);//from www.ja va2 s.co m conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream out = null; try { out = conn.getOutputStream(); out.write(bytes); } finally { // in case something blows up, while writing // the payload, we wanna close the stream: if (out != null) { out.close(); } } return conn; }
From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java
public static Map<String, String> sendToServer(String epPostFix, Map<String, String> params, String option, Context context) throws IOException { String response = null;/*from ww w. j a va2 s . c o m*/ Map<String, String> response_params = new HashMap<String, String>(); String endpoint = CommonUtilities.SERVER_URL + epPostFix; SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE); String ipSaved = mainPref.getString("ip", ""); if (ipSaved != null && ipSaved != "") { endpoint = CommonUtilities.SERVER_PROTOCOL + ipSaved + ":" + CommonUtilities.SERVER_PORT + CommonUtilities.SERVER_APP_ENDPOINT + epPostFix; } URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; HttpsURLConnection sConn = null; try { if (url.getProtocol().toLowerCase().equals("https")) { sConn = (HttpsURLConnection) url.openConnection(); sConn = getTrustedConnection(context, sConn); sConn.setHostnameVerifier(WSO2MOBILE_HOST); conn = sConn; } else { conn = (HttpURLConnection) url.openConnection(); } conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod(option); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Connection", "close"); // post the request int status = 0; Log.v("Check verb", option); if (!option.equals("DELETE")) { OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response status = conn.getResponseCode(); Log.v("Response Status", status + ""); InputStream inStream = conn.getInputStream(); response = inputStreamAsString(inStream); response_params.put("response", response); Log.v("Response Message", response); response_params.put("status", String.valueOf(status)); } else { status = Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL); } if (status != Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL) && status != Integer.valueOf(CommonUtilities.REGISTERATION_SUCCESSFUL)) { throw new IOException("Post failed with error code " + status); } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (conn != null) { conn.disconnect(); } } return response_params; }
From source file:com.vizury.PushNotification.Engine.Sender.java
/** * Makes an HTTP POST request to a given endpoint. * <p/>/* w ww.j a v a2s .c o m*/ * <p/> * <strong>Note: </strong> the returned connected should not be disconnected, * otherwise it would kill persistent connections made using Keep-Alive. * * @param url endpoint to post the request. * @param contentType type of request. * @param body body of the request. * @return the underlying connection. * @throws java.io.IOException propagated from underlying methods. */ protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { logger.warn("URL does not use https: " + url); } logger.debug("Sending POST to " + url); logger.debug("POST body: " + body); byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); try { out.write(bytes); } finally { close(out); } return conn; }
From source file:com.androidex.volley.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * //from www. j a va 2s . co m * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (String key : multipartParams.keySet()) { MultiPartParam param = multipartParams.get(key); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (String key : filesToUpload.keySet()) { File file = new File(filesToUpload.get(key)); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, key, file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength = 0; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
From source file:com.volley.air.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * /*from w ww.ja va2 s. com*/ * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (Entry<String, MultiPartParam> entry : multipartParams.entrySet()) { MultiPartParam param = entry.getValue(); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, entry.getKey())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (Entry<String, String> entry : filesToUpload.entrySet()) { File file = new File(entry.getValue()); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, entry.getKey(), file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }