List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.webcohesion.ofx4j.client.net.OFXV1Connection.java
/** * Send the specified buffer to the specified URL. * * @param url The URL./*from w w w .j a va2 s.c o m*/ * @param outBuffer The buffer. * @return The response. */ protected InputStream sendBuffer(URL url, ByteArrayOutputStream outBuffer) throws IOException, OFXConnectionException { HttpURLConnection connection = openConnection(url); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-ofx"); connection.setRequestProperty("Content-Length", String.valueOf(outBuffer.size())); connection.setRequestProperty("Accept", "*/*, application/x-ofx"); connection.setDoOutput(true); connection.connect(); OutputStream out = connection.getOutputStream(); out.write(outBuffer.toByteArray()); InputStream in; int responseCode = connection.getResponseCode(); if (responseCode >= 200 && responseCode < 300) { in = connection.getInputStream(); } else if (responseCode >= 400 && responseCode < 500) { throw new OFXServerException("Error with client request: " + connection.getResponseMessage(), responseCode); } else { throw new OFXServerException( "Invalid response code from OFX server: " + connection.getResponseMessage(), responseCode); } return in; }
From source file:com.edduarte.vokter.job.JobManager.java
private boolean sendResponse(final String clientUrl, final String input) { try {//from w w w . ja v a 2s. c o m URL targetUrl = new URL(clientUrl); HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection(); httpConnection.setDoOutput(true); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "application/json"); OutputStream outputStream = httpConnection.getOutputStream(); outputStream.write(input.getBytes()); outputStream.flush(); int responseCode = httpConnection.getResponseCode(); httpConnection.disconnect(); return responseCode == 200; } catch (IOException ex) { logger.error(ex.getMessage(), ex); } return false; }
From source file:com.trk.aboutme.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/*w w w .j a v a2 s. com*/ * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @Deprecated 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); } Utility.logd("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()) { 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:dk.clarin.tools.workflow.java
/** * Sends an HTTP GET request to a url/*from w w w. j a va 2s .c o m*/ * * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search") * @param requestString - all the request parameters (Example: "param1=val1¶m2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself * @return - The response from the end point */ public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat, String filename, String jobID, boolean postmethod) { int code = 0; String message = ""; //String filelist; if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) { // Send a GET or POST request to the servlet try { // Construct data String requestResult = ""; String urlStr = endpoint; if (postmethod) // HTTP POST { logger.debug("HTTP POST"); StringReader input = new StringReader(requestString); StringWriter output = new StringWriter(); URL endp = new URL(endpoint); HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endp.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(input, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endp + " ?): " + e); } finally { if (urlc != null) { code = urlc.getResponseCode(); if (code == 200) { got200(result, BracMat, filename, jobID, urlc.getInputStream()); } else { InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); requestResult = output.toString(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } logger.debug("urlc.getResponseCode() == {}", code); message = urlc.getResponseMessage(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } urlc.disconnect(); } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } //requestResult = output.toString(); logger.debug("postData returns " + requestResult); } else // HTTP GET { logger.debug("HTTP GET"); // Send data if (requestString != null && requestString.length() > 0) { urlStr += "?" + requestString; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.connect(); // Cast to a HttpURLConnection if (conn instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) conn; code = httpConnection.getResponseCode(); logger.debug("httpConnection.getResponseCode() == {}", code); message = httpConnection.getResponseMessage(); BufferedReader rd; StringBuilder sb = new StringBuilder(); ; //String line; if (code == 200) { got200(result, BracMat, filename, jobID, httpConnection.getInputStream()); } else { // Get the error response rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream())); int nextChar; while ((nextChar = rd.read()) != -1) { sb.append((char) nextChar); } rd.close(); requestResult = sb.toString(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } logger.debug("Job " + jobID + " receives status code [" + code + "] from tool."); } catch (Exception e) { //jobs = 0; // No more jobs to process now, probably the tool is not reachable logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage()); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } } else { //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint + ")"); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } return code; }
From source file:com.eyekabob.util.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 www. ja va2 s . c o m * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ // COFFBR01 MODIFIED 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); } Util.logd("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()) { Object value = params.get(key); if (value instanceof byte[]) { dataparams.putByteArray(key, (byte[]) value); } } // 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.lostad.app.base.util.RequestUtil.java
/** * HTTP??????,??? /*from w w w. j a v a 2 s .c om*/ * @param actionUrl * @param params ? key???,value? * @param files * @throws Exception */ public static String postFile(String actionUrl, Map<String, String> params, FormFile[] files, String token) throws Exception { try { String BOUNDARY = "---------7d4a6d158c9"; //? String MULTIPART_FORM_DATA = "multipart/form-data"; URL url = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true);//? conn.setDoOutput(true);//? conn.setUseCaches(false);//?Cache conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); conn.setRequestProperty("token", token); //???? StringBuilder sb = new StringBuilder(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) {//? sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); sb.append(entry.getValue()); sb.append("\r\n"); } } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes());//???? //?? for (FormFile file : files) { StringBuilder split = new StringBuilder(); split.append("--"); split.append(BOUNDARY); split.append("\r\n"); split.append("Content-Disposition: form-data;name=\"" + file.getFormname() + "\";filename=\"" + file.getFilname() + "\"\r\n"); split.append("Content-Type: " + file.getContentType() + "\r\n\r\n"); outStream.write(split.toString().getBytes()); outStream.write(file.getData(), 0, file.getData().length); outStream.write("\r\n".getBytes()); } byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//?? outStream.write(end_data); outStream.flush(); int cah = conn.getResponseCode(); if (cah != 200) throw new RuntimeException("url"); InputStream is = conn.getInputStream(); int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } outStream.close(); conn.disconnect(); return b.toString(); } catch (Exception e) { throw e; } }
From source file:org.callimachusproject.test.WebResource.java
public void post(String type, byte[] body) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", type); con.setDoOutput(true);/*from ww w. j a v a 2 s . c om*/ OutputStream req = con.getOutputStream(); try { req.write(body); } finally { req.close(); } Assert.assertEquals(con.getResponseMessage(), 204, con.getResponseCode()); }
From source file: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// w ww . j ava 2 s. c om * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @Deprecated public static String openUrl(String url, String method, Bundle params) throws 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); } Utility.logd("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()) { 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()); try { 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(); } finally { os.close(); } } 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.nofuturecorp.www.connector.Database.java
/** * Make a post request to the PHP URL for process request and get data in JSON format * @param json with data to send/*from w ww . j av a 2s. c o m*/ * @return JSON with data received * @throws IOException * @throws DatabaseException */ private String makePostRequest(String json) throws IOException, DatabaseException { if (json == null) { throw new NullPointerException("json cannot be null"); } if (!ignoreSecureProtocol && url.toUpperCase().startsWith("HTTPS")) { throw new SecureProtocolException( "URL Protocol is not valid. Please use HTTPS or set true ignore secure protocol"); } StringBuffer data = null; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(("isTransaction=" + isTransaction + "&data=" + json).getBytes()); os.flush(); os.close(); int response = con.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String line = null; data = new StringBuffer(); while ((line = reader.readLine()) != null) { data.append(line); } String js = data.substring(data.indexOf("{")); return js; } else { throw new DatabaseException("HTTP connection fails. Response code: " + response); } }
From source file:com.captix.scan.social.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /* ww w . j a va2 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); 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")) { @SuppressWarnings("deprecation") 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; }