List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public XML postXML(String url, XML data) throws IOException, TransformerException, SAXException, ParserConfigurationException { logger.log(Level.INFO, "Posting document to {0}", url); // Build and connect HttpURLConnection connection = buildConnection(url); connection.setDoOutput(true);// w ww .j a v a 2 s.c o m OutputStream out = connection.getOutputStream(); connection.connect(); // Write the document Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(new DOMSource(data.getDocument()), new StreamResult(out)); out.flush(); out.close(); // Check for errors checkForErrors(connection); // Get the result Document document = buildDocument(connection.getInputStream()); return disconnectAndReturn(connection, new XML(document)); }
From source file:br.random.util.facebookintegration.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 ww.jav a 2 s. co 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.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.familygraph.android.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /* ww w . jav a 2s . 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("FamilyGraph-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FamilyGraphAndroidSDK"); 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 FamilyGraph // error response = read(conn.getErrorStream()); } return response; }
From source file:com.qburst.android.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 va2 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); } 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.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.intravel.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/*from w w w .ja v a 2 s . c om*/ * @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); } // else{ // 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.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.amgems.uwschedule.api.uw.LoginAuthenticator.java
/** * Executes a login authentication request. * * Stores the response from the execution and the cookie string if authentication * was valid. The execute method should only be called once. Behavior is unspecified * for multiple calls./*ww w. j av a 2s .c o m*/ * * Note that this method is blocking and should <b>not</b> be called on the UI thread. */ public void execute() { // List of cookies received from server List<String> cookieList = null; try { lock.lock(); mHandler.post(new Runnable() { @Override public void run() { mJsWebview.loadUrl(NetUtils.REGISTRATION_URL); } }); while (!mLoadingFinished) { htmlCallbackCondition.await(); } } catch (InterruptedException e) { Log.d(getClass().getSimpleName(), "Html callback thread interrupted before it could be signaled"); } finally { lock.unlock(); } try { List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); InputStream htmlInputStream = new ByteArrayInputStream(mHtml.getBytes()); BufferedReader reader = new BufferedReader(new InputStreamReader(htmlInputStream)); // Captures and injects required post parameters for login postParameters.add(new BasicNameValuePair("user", mUsername)); postParameters.add(new BasicNameValuePair("pass", mPassword)); captureHiddenParameters(reader, postParameters); HttpURLConnection connection = mHttpClient .buildWriteReadableConnection(new URL(NetUtils.BASE_REQUEST_URL)); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream())); // Reads stream from response and stores any received cookies try { cookieList = getAuthCookies(connection, bufferedWriter, postParameters); // Valid cookie was returned - authentication was a success if (cookieList != null) { mCookiesValue = cookieList.get(0); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String postLoginHtml = ""; String line; while ((line = reader.readLine()) != null) { postLoginHtml += line; } postParameters.clear(); captureHiddenParameters( new BufferedReader( new InputStreamReader(new ByteArrayInputStream(postLoginHtml.getBytes()))), postParameters); mCookiesValue = postLoginHtml.substring(postLoginHtml.indexOf("pubcookie_g"), postLoginHtml.indexOf("==\">") + 2); mCookiesValue = "pubcookie_g=" + mCookiesValue.substring("pubcookie_g\" value=\"".length()) + ";"; } } finally { connection.disconnect(); } } catch (MalformedURLException e) { mResponse = Response.SERVER_ERROR; } catch (IOException e) { mResponse = Response.NETWORK_ERROR; } if (mResponse == null) { if (cookieList != null) { mResponse = Response.OK; } else { // No cookies returned, username/password incorrect mResponse = Response.AUTHENTICATION_ERROR; } } }
From source file:com.notonthehighstreet.ratel.internal.utility.HttpRequest.java
public int call(final HttpURLConnection connection, final String method, final Map<String, String> headers, final Object body) throws IOException { connection.setConnectTimeout(TEN_SECONDS); connection.setReadTimeout(TEN_SECONDS); connection.setRequestMethod(method); for (final Map.Entry<String, String> header : headers.entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); }//from w w w .ja va2 s . c o m connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), body); return connection.getResponseCode(); }
From source file:org.teiid.arquillian.IntegrationTestRestWebserviceGeneration.java
private String httpCall(String url, String method, String params) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true);/*from w ww . j ava 2 s .co m*/ if (method.equalsIgnoreCase("post")) { OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(params); wr.flush(); } int code = connection.getResponseCode(); if (code >= 400) { throw new TeiidRuntimeException(String.valueOf(code)); } return ObjectConverterUtil .convertToString(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8"))); }
From source file:de.akquinet.engineering.vaadinator.timesheet.service.AbstractCouchDbService.java
protected JSONObject putCouch(String urlPart, JSONObject content) throws IOException, MalformedURLException, JSONException { HttpURLConnection couchConn = null; BufferedReader couchRead = null; OutputStreamWriter couchWrite = null; try {/*from w w w. j a v a2s . c o m*/ couchConn = (HttpURLConnection) (new URL(couchUrl + (couchUrl.endsWith("/") ? "" : "/") + urlPart)) .openConnection(); couchConn.setRequestMethod("PUT"); couchConn.setDoInput(true); couchConn.setDoOutput(true); couchWrite = new OutputStreamWriter(couchConn.getOutputStream()); couchWrite.write(content.toString()); couchWrite.flush(); couchRead = new BufferedReader(new InputStreamReader(couchConn.getInputStream())); StringBuffer jsonBuf = new StringBuffer(); String line = couchRead.readLine(); while (line != null) { jsonBuf.append(line); line = couchRead.readLine(); } JSONObject couchObj = new JSONObject(jsonBuf.toString()); return couchObj; } finally { if (couchRead != null) { couchRead.close(); } if (couchWrite != null) { couchWrite.close(); } if (couchConn != null) { couchConn.disconnect(); } } }
From source file:fyp.project.asyncTask.Http_GetPost.java
public void POST(String url, String val) throws IOException { HttpURLConnection urlConnection = null; try {// w w w.j av a 2s. c o m URL url2 = new URL(url); urlConnection = (HttpURLConnection) url2.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(10000); urlConnection.setDoOutput(true); String data = val; OutputStream out = urlConnection.getOutputStream(); out.write(data.getBytes()); out.flush(); out.close(); int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { InputStream is = urlConnection.getInputStream(); String result = convertInputStreamToString(is); webpage_output = result; } } catch (Exception e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } }