List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:Transcriber.java
public String process(ByteArrayOutputStream wav) throws Exception { // Create connection URL url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "audio/l16; rate=16000"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36"); //connection.setUseCaches(false); connection.setDoOutput(true);//from ww w .j a va 2 s . c o m // Write wav to request body OutputStream out = connection.getOutputStream(); //InputStream in = new FileInputStream("hello.wav"); wav.writeTo(out); out.close(); //Get Response BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; String ignore = in.readLine(); // skip first empty results line //System.out.println("ignore = " + ignore); StringBuilder responseData = new StringBuilder(); while ((line = in.readLine()) != null) { responseData.append(line); } String result = responseData.toString(); if (!result.isEmpty()) { JSONObject obj = new JSONObject(result); String text = obj.getJSONArray("result").getJSONObject(0).getJSONArray("alternative").getJSONObject(0) .getString("transcript"); return text; } return ""; }
From source file:barcamp.com.facebook.android.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * 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//from ww w.j a v a 2s .c o m * @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); 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.get(key) instanceof byte[]) { //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.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:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java
private void checkForIndexTemplate() { try {//from w w w .ja v a2s.com HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD"); connection.disconnect(); boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND; // nothing there, lets create it if (isTemplateMissing) { LOGGER.debug("No metrics template found in elasticsearch. Adding..."); HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT"); JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream()); json.writeStartObject(); json.writeStringField("template", index + "*"); json.writeObjectFieldStart("mappings"); json.writeObjectFieldStart("_default_"); json.writeObjectFieldStart("_all"); json.writeBooleanField("enabled", false); json.writeEndObject(); json.writeObjectFieldStart("properties"); json.writeObjectFieldStart("name"); json.writeObjectField("type", "string"); json.writeObjectField("index", "not_analyzed"); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.flush(); putTemplateConnection.disconnect(); if (putTemplateConnection.getResponseCode() != HttpStatus.OK.value()) { LOGGER.error( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage()); } } checkedForIndexTemplate = true; } catch (IOException e) { LOGGER.error("Error when checking/adding metrics template to elasticsearch", e); } }
From source file:info.icefilms.icestream.browse.Location.java
protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie, Callback callback) {/*from ww w . j a v a 2s . co m*/ // Declare our buffer ByteArrayBuffer byteArrayBuffer; try { // Setup the connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0"); urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString()); if (sendCookie != null) urlConnection.setRequestProperty("Cookie", sendCookie); if (sendData != null) { urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setDoOutput(true); } urlConnection.setConnectTimeout(callback.GetConnectionTimeout()); urlConnection.setReadTimeout(callback.GetConnectionTimeout()); urlConnection.connect(); // Get the output stream and send the data if (sendData != null) { OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(sendData.getBytes()); outputStream.flush(); outputStream.close(); } // Get the cookie if (getCookie != null) { // Clear the string builder getCookie.delete(0, getCookie.length()); // Loop thru the header fields String headerName; String cookie; for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) { if (headerName.equalsIgnoreCase("Set-Cookie")) { // Get the cookie cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i)); // Add it to the string builder if (cookie != null) getCookie.append(cookie); break; } } } // Get the input stream InputStream inputStream = urlConnection.getInputStream(); // For some reason we can actually get a null InputStream instead of an exception if (inputStream == null) { Log.e("Ice Stream", "Page download failed. Unable to create Input Stream."); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_download_error); } urlConnection.disconnect(); return null; } // Get the file size final int fileSize = urlConnection.getContentLength(); // Create our buffers byte[] byteBuffer = new byte[2048]; byteArrayBuffer = new ByteArrayBuffer(2048); // Download the page int amountDownloaded = 0; int count; while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) { // Check if we got canceled if (callback.IsCancelled()) { inputStream.close(); urlConnection.disconnect(); return null; } // Add data to the buffer byteArrayBuffer.append(byteBuffer, 0, count); // Update the downloaded amount amountDownloaded += count; } // Close the connection inputStream.close(); urlConnection.disconnect(); // Check for amount downloaded calculation error if (fileSize != -1 && amountDownloaded != fileSize) { Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not " + "match reported content length (" + fileSize + " bytes)."); } } catch (SocketTimeoutException exception) { Log.e("Ice Stream", "Page download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_timeout_error); } return null; } catch (IOException exception) { Log.e("Ice Stream", "Page download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_download_error); } return null; } // Convert things to a string return new String(byteArrayBuffer.toByteArray()); }
From source file:com.enefsy.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * 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/*w w w. j a v a 2 s . c o m*/ * @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); } 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()) { Object parameter = params.get(key); if (parameter instanceof byte[]) { dataparams.putByteArray(key, (byte[]) parameter); } } // 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.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:com.xeiam.xchange.rest.HttpTemplate.java
/** * Executes an HTTP request with the given parameters. * /*from w w w. ja v a 2 s . c o m*/ * @param method The HTTP method (e.g. GET, POST etc) * @param urlString A string representation of a URL * @param httpHeaders The HTTP headers (will override the defaults) * @param requestBody The request body (typically only for POST method) * @return The contents of the response body as String */ private String executeRequest(String urlString, String requestBody, Map<String, String> httpHeaders, HttpMethod method) { Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders cannot be null"); log.debug("Executing {} request at {}", method, urlString); log.trace("Request body = {}", requestBody); log.trace("Request headers = {}", httpHeaders); String responseString = ""; HttpURLConnection connection = null; try { int contentLength = requestBody == null ? 0 : requestBody.length(); connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (contentLength > 0) { // Write the request body connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8)); } // Begin reading the response checkHttpStatusCode(connection); // Minimize the impact of the HttpURLConnection on the job of getting the data String responseEncoding = getResponseEncoding(connection); InputStream inputStream = connection.getInputStream(); // Get the data responseString = readInputStreamAsEncodedString(inputStream, responseEncoding); } catch (MalformedURLException e) { throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e); } catch (IOException e) { throw new HttpException("Problem " + method + "ing (IO)", e); } finally { // This is a bit messy if (connection != null) { connection.disconnect(); } } log.debug("Response body: {}", responseString); return responseString; }
From source file:fr.mixit.android.utils.NetworkUtils.java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) static ResponseHttp getInputStreamFromHttpUrlConnection(String url, boolean isPost, String args) { final ResponseHttp myResponse = new ResponseHttp(); HttpURLConnection urlConnection = null; if (cookieManager == null) { cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); }/*from www . ja va2 s. c o m*/ try { String urlWithParams = url; if (!isPost && args != null) { urlWithParams = getGetURL(url, args); } final URL urlObject = new URL(urlWithParams); urlConnection = (HttpURLConnection) urlObject.openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT); urlConnection.setReadTimeout(SOCKET_TIMEOUT); // if (cookieSession != null) { // cookieManager.getCookieStore().removeAll(); // cookieManager.getCookieStore().addCookie(cookieSession); // } if (isPost) { urlConnection.setDoOutput(true); } // urlConnection.connect(); if (isPost && args != null) { final byte[] params = args.getBytes(HTTP.UTF_8); urlConnection.setFixedLengthStreamingMode(params.length);// or urlConnection.setChunkedStreamingMode(0); final OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(params); } myResponse.status = urlConnection.getResponseCode(); if (DEBUG_MODE) { Log.d(TAG, "Status code : " + myResponse.status); } myResponse.jsonText = getJson(urlConnection.getInputStream()); } catch (final MalformedURLException e) { if (DEBUG_MODE) { Log.e(TAG, "The URL is malformatted", e); } } catch (final IllegalAccessError e) { if (DEBUG_MODE) { Log.e(TAG, "setDoOutput after openning a connection or already done"); } } catch (final UnsupportedEncodingException e) { if (DEBUG_MODE) { Log.e(TAG, "UTF8 unsupported for args", e); } } catch (final IllegalStateException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } catch (final IllegalArgumentException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } catch (final IOException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return myResponse; }
From source file:com.ble.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * //from w w w . j av a 2 s. c o m * 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.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:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public byte[] post(String url, byte[] data) throws IOException { // Build and connect HttpURLConnection connection = buildConnection(url); connection.setDoOutput(true);//from w ww . ja va 2 s . co m 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.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public String postString(String url, String data) throws IOException { // Build and connect HttpURLConnection connection = buildConnection(url); connection.setDoOutput(true);/*from ww w.j a v a 2s . c o m*/ connection.setDoInput(true); connection.connect(); // Send the request connection.getOutputStream().write(data.getBytes("ISO-8859-1")); connection.getOutputStream().flush(); connection.getOutputStream().close(); // Check for errors checkForErrors(connection); // Get the result return disconnectAndReturn(connection, IOUtils.toString(connection.getInputStream(), "ISO-8859-1")); }