List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:de.ingrid.communication.authentication.BasicSchemeConnector.java
public boolean connect(Socket socket, String host, int port, String userName, String password) throws IOException { DataInputStream dataInput = createInput(socket); DataOutputStream dataOutput = createOutput(socket); StringBuffer errorBuffer = new StringBuffer(); String command = createConnectCommand(host, port, userName, password); errorBuffer.append(command);/*from w w w . ja v a 2 s .c o m*/ dataOutput.write(command.getBytes()); dataOutput.flush(); boolean success = readMessageFromHttpProxy(dataInput, errorBuffer); if (!success) { if (LOG.isEnabledFor(Level.WARN)) { LOG.error(errorBuffer); } } return success; }
From source file:com.esri.geoevent.test.tools.GetMapServiceCountRunnable.java
private int getMsLayerCount(String url) { int cnt = -1; try {//w ww . j a v a 2 s . c om URL obj = new URL(url + "/query"); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); con.setRequestProperty("Accept", "text/plain"); String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly=" + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result String jsonString = response.toString(); JSONTokener tokener = new JSONTokener(jsonString); JSONObject root = new JSONObject(tokener); cnt = root.getInt("count"); } catch (Exception e) { cnt = -2; } finally { return cnt; } }
From source file:com.snaplogic.snaps.lunex.RequestProcessor.java
public String execute(RequestBuilder rBuilder) throws MalformedURLException, IOException { try {/*from w w w. ja va 2 s . com*/ URL api_url = new URL(rBuilder.getURL()); HttpURLConnection httpUrlConnection = (HttpURLConnection) api_url.openConnection(); httpUrlConnection.setRequestMethod(rBuilder.getMethod().toString()); httpUrlConnection.setDoInput(true); httpUrlConnection.setDoOutput(true); if (rBuilder.getSnapType() != LunexSnaps.Read) { rBuilder.getHeaders().add(Pair.of(CONTENT_LENGTH, rBuilder.getRequestBodyLenght())); } for (Pair<String, String> header : rBuilder.getHeaders()) { if (!StringUtils.isEmpty(header.getKey()) && !StringUtils.isEmpty(header.getValue())) { httpUrlConnection.setRequestProperty(header.getKey(), header.getValue()); } } log.debug(String.format(LUNEX_HTTP_INFO, rBuilder.getSnapType(), rBuilder.getURL(), httpUrlConnection.getRequestProperties().toString())); if (rBuilder.getSnapType() != LunexSnaps.Read) { String paramsJson = null; if (!StringUtils.isEmpty(paramsJson = rBuilder.getRequestBody())) { DataOutputStream cgiInput = new DataOutputStream(httpUrlConnection.getOutputStream()); log.debug(String.format(LUNEX_HTTP_REQ_INFO, paramsJson)); cgiInput.writeBytes(paramsJson); cgiInput.flush(); IOUtils.closeQuietly(cgiInput); } } List<String> input = null; StringBuilder response = new StringBuilder(); try (InputStream iStream = httpUrlConnection.getInputStream()) { input = IOUtils.readLines(iStream); } catch (IOException ioe) { log.warn(String.format(INPUT_STREAM_ERROR, ioe.getMessage())); try (InputStream eStream = httpUrlConnection.getErrorStream()) { if (eStream != null) { input = IOUtils.readLines(eStream); } else { response.append(String.format(INPUT_STREAM_ERROR, ioe.getMessage())); } } catch (IOException ioe1) { log.warn(String.format(INPUT_STREAM_ERROR, ioe1.getMessage())); } } statusCode = httpUrlConnection.getResponseCode(); log.debug(String.format(HTTP_STATUS, statusCode)); if (input != null && !input.isEmpty()) { for (String line : input) { response.append(line); } } return formatResponse(response, rBuilder); } catch (MalformedURLException me) { log.error(me.getMessage(), me); throw me; } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); throw ioe; } catch (Exception ex) { log.error(ex.getMessage(), ex); throw ex; } }
From source file:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java
private String updateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) { HttpURLConnection conn = null; String fileId = null;//from w w w.ja va2 s .c o m String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId + "?uploadType=media"; try { URL url = new URL(fileUpdateUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", getMimeTypeFromFileName(fileName)); conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length)); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(10000); conn.setReadTimeout(30000); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.write(fileContents); wr.flush(); wr.close(); String fileMetadata = Streams.getStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); LOG.debug("File updated : " + fileId); } catch (Exception e) { LOG.error("Could not update contents", e); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:de.kasoki.jfeedly.helper.HTTPConnections.java
private String sendRequest(String apiUrl, String parameters, boolean isAuthenticated, RequestType type, String contentType) {/*from ww w . j ava 2s . c om*/ try { String url = this.jfeedlyHandler.getBaseUrl() + apiUrl.replaceAll(" ", "%20"); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestProperty("User-Agent", "jfeedly"); if (!contentType.isEmpty()) { con.setRequestProperty("Content-Type", contentType); } if (isAuthenticated) { con.setRequestProperty("Authorization", "OAuth " + this.jfeedlyHandler.getConnection().getAccessToken()); } // Send request header if (type == RequestType.POST) { con.setRequestMethod("POST"); con.setDoOutput(true); DataOutputStream writer = new DataOutputStream(con.getOutputStream()); writer.write(parameters.getBytes()); writer.flush(); writer.close(); } else if (type == RequestType.GET) { con.setRequestMethod("GET"); } else if (type == RequestType.DELETE) { con.setRequestMethod("DELETE"); } else { System.err.println("jfeedly: Unkown RequestType " + type); } int responseCode = con.getResponseCode(); if (jfeedlyHandler.getVerbose()) { System.out.println("\n" + type + " to: " + url); System.out.println("content : " + parameters); System.out.println("\nResponse Code : " + responseCode); } BufferedReader in = null; // if error occurred if (responseCode >= 400) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String serverResponse = response.toString(); if (jfeedlyHandler.getVerbose()) { //print response String printableResponse = format(serverResponse); if (responseCode >= 400) { System.err.println(printableResponse); } else { System.out.println(printableResponse); } } return serverResponse; } catch (IOException ex) { ex.printStackTrace(); } return null; }
From source file:com.orchestra.portale.profiler.FbProfiler.java
private HttpURLConnection addParameter(HttpURLConnection connection, Map<String, String> params) throws IOException { if (params != null) { String param_string = ""; for (String k : params.keySet()) { param_string += k + "=" + params.get(k) + "&"; }/*from w w w . j a va 2 s .c o m*/ param_string = param_string.substring(0, param_string.length() - 1); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(param_string); wr.flush(); wr.close(); } return connection; }
From source file:com.ebay.erl.mobius.core.model.TupleTest.java
/** * test serialization and de-serialization * /*from w ww .j av a 2s. c om*/ * @throws IOException */ @Test public void test_serde() throws IOException { Tuple t = this.prepareTupe(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bos); t.write(out); out.flush(); out.close(); DataInputStream in = new DataInputStream(new ByteArrayInputStream(bos.toByteArray())); Tuple nt = new Tuple(); nt.readFields(in); // ordering doesn't matter nt.setSchema(new String[] { "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "C11", "C12" }); this._assertp_tuple(nt); }
From source file:de.ingrid.iplug.csw.dsc.cswclient.impl.XMLPostRequest.java
/** * Send the given request to the server. * @param serverURL//from w w w. j ava 2s . c o m * @param payload * @return Document * @throws Exception */ protected Document sendRequest(String requestURL, OMElement payload) throws Exception { // and make the call Document result = null; HttpURLConnection conn = null; try { URL url = new URL(requestURL); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setAllowUserInteraction(false); conn.setReadTimeout(10000); conn.setDoOutput(true); conn.setRequestProperty("Content-type", "text/xml"); conn.connect(); // send the request String xmlToSend = serializeElement(payload.cloneOMElement()); if (log.isDebugEnabled()) log.debug("Request: " + xmlToSend); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(xmlToSend); wr.flush(); wr.close(); // Get response data. int code = conn.getResponseCode(); if (code >= 200 && code < 300) { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); result = builder.parse(conn.getInputStream()); } conn.disconnect(); conn = null; } catch (Exception e) { throw e; } finally { if (conn != null) conn.disconnect(); } return result; }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public void sendPost() throws Exception { String url = "https://selfsolve.apple.com/wcResults.do"; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; // Send post request con.setDoOutput(true);//from w w w. j a v a 2 s .c o m DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); }
From source file:moodle.android.moodle.helpers.MoodleWebService.java
private JSONObject getWebServiceResponse(String serverurl, String functionName, String urlParameters, int xslRawId) { JSONObject jsonobj = null;/* w w w .j a v a2 s . c o m*/ try { HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName).openConnection(); //HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName + "&moodlewsrestformat=json").openConnection(); con.setConnectTimeout(30000); con.setReadTimeout(30000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Language", "en-US"); con.setDoOutput(true); con.setUseCaches(false); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); Log.d("URLParameters: ", urlParameters.toString()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Get Response InputStream is = con.getInputStream(); Source xmlSource = new StreamSource(is); Source xsltSource = new StreamSource(context.getResources().openRawResource(xslRawId)); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); StringWriter writer = new StringWriter(); trans.transform(xmlSource, new StreamResult(writer)); String jsonstr = writer.toString(); jsonstr = jsonstr.replace("<div class=\"no-overflow\"><p>", ""); jsonstr = jsonstr.replace("</p></div>", ""); jsonstr = jsonstr.replace("<p>", ""); jsonstr = jsonstr.replace("</p>", ""); Log.d("TransformObject: ", jsonstr); jsonobj = new JSONObject(jsonstr); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonobj; }