List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:software.uncharted.util.HTTPUtil.java
public static String post(String urlToRead, String postData) { URL url;/* w w w.j a v a2 s. c om*/ HttpURLConnection conn; try { url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(postData); wr.flush(); wr.close(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; InputStream is = conn.getInputStream(); while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toString(); } catch (Exception e) { e.printStackTrace(); System.err.println("Failed to read URL: " + urlToRead + " <" + e.getMessage() + ">"); } return null; }
From source file:Main.java
public static String httpPost(String urlStr, List<NameValuePair> params) { String paramsEncoded = ""; if (params != null) { paramsEncoded = URLEncodedUtils.format(params, "UTF-8"); }//www .jav a 2s . com String result = null; URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; try { url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Charset", "utf-8"); DataOutputStream dop = new DataOutputStream(connection.getOutputStream()); dop.writeBytes(paramsEncoded); dop.flush(); dop.close(); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }
From source file:com.telefonica.iot.perseo.test.Help.java
public static Res sendMethod(String url, String body, String method) throws Exception { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod(method);//from www .j av a2 s .c o m con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); String responseBody = getBodyResponse(con); return new Res(responseCode, responseBody); }
From source file:com.lightboxtechnologies.spectrum.FsEntryHBaseInputFormat.java
static String convertScanToString(Scan scan) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dos = null; try {/*from w w w .jav a 2s .com*/ dos = new DataOutputStream(out); scan.write(dos); dos.close(); return Base64.encodeBytes(out.toByteArray()); } finally { IOUtils.closeQuietly(dos); } }
From source file:com.shopgun.android.sdk.network.impl.HttpURLNetwork.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true);//from w w w.j av a 2 s. c o m connection.addRequestProperty("Content-Type", request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
From source file:javaphpmysql.JavaPHPMySQL.java
public static void sendPost() { //Creamos un objeto JSON JSONObject jsonObj = new JSONObject(); //Aadimos el nombre, apellidos y email del usuario jsonObj.put("nombre", nombre); jsonObj.put("apellidos", apellidos); jsonObj.put("email", email); //Creamos una lista para almacenar el JSON List l = new LinkedList(); l.addAll(Arrays.asList(jsonObj)); //Generamos el String JSON String jsonString = JSONValue.toJSONString(l); System.out.println("JSON GENERADO:"); System.out.println(jsonString); System.out.println(""); try {// www . jav a 2s . co m //Codificar el json a URL jsonString = URLEncoder.encode(jsonString, "UTF-8"); //Generar la URL String url = SERVER_PATH + "listenPost.php"; //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON URL obj = new URL(url); //Creamos un objeto de conexin HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //Aadimos la cabecera con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //Creamos los parametros para enviar String urlParameters = "json=" + jsonString; // Enviamos los datos por POST con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Capturamos la respuesta del servidor 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); } //Mostramos la respuesta del servidor por consola System.out.println(response); //cerramos la conexin in.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:TestPipes.java
public static void writeData(OutputStream os) { try {//from w ww. j av a2 s . com DataOutputStream out = new DataOutputStream(new BufferedOutputStream(os)); int[] numArray = { 1, 2, 3, 4, 5 }; for (int i = 0; i < numArray.length; i++) { out.writeInt(numArray[i]); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:de.cubeisland.engine.core.util.McUUID.java
private static HttpURLConnection postQuery(ArrayNode node, int page) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(MOJANG_API_URL_NAME_UUID + page).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setUseCaches(false);//from w w w. ja v a2 s . c o m con.setDoInput(true); con.setDoOutput(true); DataOutputStream writer = new DataOutputStream(con.getOutputStream()); writer.write(node.toString().getBytes()); writer.close(); return con; }
From source file:ro.fortsoft.matilda.util.RecaptchaUtils.java
public static boolean verify(String recaptchaResponse, String secret) { if (StringUtils.isNullOrEmpty(recaptchaResponse)) { return false; }//from ww w . j a v a2s . c o m boolean result = false; try { URL url = new URL("https://www.google.com/recaptcha/api/siteverify"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // add request header connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String postParams = "secret=" + secret + "&response=" + recaptchaResponse; // log.debug("Post parameters '{}'", postParams); // send post request connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(postParams); outputStream.flush(); outputStream.close(); int responseCode = connection.getResponseCode(); log.debug("Response code '{}'", responseCode); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // print result log.debug("Response '{}'", response.toString()); // parse JSON response and return 'success' value ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(response.toString()); JsonNode nameNode = rootNode.path("success"); result = nameNode.asBoolean(); } catch (Exception e) { log.error(e.getMessage(), e); } return result; }
From source file:com.microsoft.office365.connectmicrosoftgraph.ConnectUnitTests.java
@BeforeClass public static void getAccessTokenUsingPasswordGrant() throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException { URL url = new URL(TOKEN_ENDPOINT); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); String urlParameters = String.format( "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE, URLEncoder.encode(Constants.MICROSOFT_GRAPH_API_ENDPOINT_RESOURCE_ID, "UTF-8"), clientId, username, password);//w w w . j a va 2s .c o m connection.setRequestMethod(REQUEST_METHOD); connection.setRequestProperty("Content-Type", CONTENT_TYPE); connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length)); connection.setDoOutput(true); DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.writeBytes(urlParameters); dataOutputStream.flush(); dataOutputStream.close(); connection.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JsonParser jsonParser = new JsonParser(); JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString()); accessToken = grantResponse.get("access_token").getAsString(); }