List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:copter.ServerConnection.java
/** * this function make a post request to server and get response it sends * copter IP Address, Unique ID and Name * * @param ipAddress// ww w .ja v a 2s . c o m */ private String registerCopterOnServer(String ipAddress) { String serverHost = Config.getInstance().getString("main", "server_host"); String copter_unique_id = Config.getInstance().getString("copter", "unique_id"); String copter_name = Config.getInstance().getString("copter", "name"); URL url; try { url = new URL("http://" + serverHost + Config.getInstance().getString("main", "register_copter_url")); HttpURLConnection con = (HttpURLConnection) url.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 = "copter_ip=" + ipAddress + "&unique_id=" + copter_unique_id + "&name=" + copter_name; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); logger.log("\nSending 'POST' request to URL : " + url); logger.log("Post parameters : " + urlParameters); logger.log("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String jsonResponse = response.toString(); JSONParser parser = new JSONParser(); Object obj = parser.parse(jsonResponse); JSONObject jsonObj = (JSONObject) obj; String status = (String) jsonObj.get("status"); if (status != null && status.equals("ok")) { return "ok"; } else { return (String) jsonObj.get("message"); } } catch (Exception ex) { return ex.getMessage(); } }
From source file:io.teak.sdk.Request.java
@Override public void run() { HttpsURLConnection connection = null; SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256"); String requestBody;// w w w . j a v a 2 s . c o m String hostnameForEndpoint = this.hostname; if (hostnameForEndpoint == null) { hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint); } try { ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet()); Collections.sort(payloadKeys); StringBuilder builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); if (value != null) { String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(valueString).append("&"); } else { Log.e(LOG_TAG, "Value for key: " + key + " is null."); } } builder.deleteCharAt(builder.length() - 1); String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString(); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); byte[] result = mac.doFinal(stringToSign.getBytes()); builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&"); } builder.append("sig=") .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8")); requestBody = builder.toString(); } catch (Exception e) { Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e)); return; } try { if (Teak.isDebug) { Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': " + new JSONObject(this.payload).toString(2)); } URL url = new URL("https://" + hostnameForEndpoint + this.endpoint); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length)); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); // Get Response InputStream is; if (connection.getResponseCode() < 400) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (Teak.isDebug) { String responseText = response.toString(); try { responseText = new JSONObject(response.toString()).toString(2); } catch (Exception ignored) { } Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText); } // For extending classes done(connection.getResponseCode(), response.toString()); } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:MainFrame.HttpCommunicator.java
public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel) throws MalformedURLException, IOException { BufferedReader in = null;/* w ww.jav a2 s. c o m*/ if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)); in = new BufferedReader(new InputStreamReader(stream)); } else { URL obj = new URL(SingleDataHolder.getInstance().hostAdress); HttpURLConnection con = (HttpURLConnection) 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 = "apideskviewer.getAllLessons={}"; // Send post request con.setDoOutput(true); 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 : " + SingleDataHolder.getInstance().hostAdress); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); in = new BufferedReader(new InputStreamReader(con.getInputStream())); } JSONParser parser = new JSONParser(); try { Object parsedResponse = parser.parse(in); JSONObject jsonParsedResponse = (JSONObject) parsedResponse; for (int i = 0; i < jsonParsedResponse.size(); i++) { String s = (String) jsonParsedResponse.get(String.valueOf(i)); String[] splittedPath = s.split("/"); DateFormat DF = new SimpleDateFormat("yyyyMMdd"); Date d = DF.parse(splittedPath[1].replaceAll(".bin", "")); Lesson lesson = new Lesson(splittedPath[0], d, false); String group = splittedPath[0]; String date = new SimpleDateFormat("dd.MM.yyyy").format(d); if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) { comboGroups.addItem(group); } if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) { comboDates.addItem(date); } tableModel.addLesson(lesson); } } catch (Exception ex) { } }
From source file:com.hulaki.smtp.api.ApiClient.java
private String sendRequestToApiServer(ApiRequest request) { try {//ww w. j ava2 s .c om Socket clientSocket = new Socket(this.apiServerHostname, this.apiServerPort); DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); String requestString = request.toRequestString() + "\n"; logger.trace(requestString); out.writeBytes(requestString); StringBuilder response = new StringBuilder(); logger.trace(response.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine).append("\n"); } clientSocket.close(); return response.toString(); } catch (ConnectException e) { throw new ApiException("SMTP mock not available at " + apiServerHostname + ":" + apiServerPort); } catch (IOException e) { throw new ApiException(e); } }
From source file:Main.java
public static String postMultiPart(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException { HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String[] q = filepath.split("/"); int idx = q.length - 1; try {/* w w w . ja v a 2s . c o m*/ File file = new File(filepath); FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(urlTo); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); // Upload POST Data String[] posts = post.split("&"); int max = posts.length; for (int i = 0; i < max; i++) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); String[] kv = posts[i].split("="); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: text/plain" + lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(kv[1]); outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); inputStream = connection.getInputStream(); result = convertStreamToString(inputStream); fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { Log.e("MultipartRequest", "Multipart Form Upload Error"); e.printStackTrace(); return "error"; } }
From source file:iics.Connection.java
public String excutePost(String targetURL, String urlParameters) { URL url;//from ww w. j av a 2 s .c o m HttpURLConnection connection = null; try { //Create connection url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { if (!line.equals("")) { response.append(line); } //response.append('\r'); } rd.close(); // System.out.println("gigig " + response.toString()); if (response.toString().substring(0, 8).equals("Response")) { String[] dett = response.toString().split("~~~"); det = dett[1]; create_dir(); openweb(f.toString()); } else { //System.out.println("err "+ex.getMessage()); JOptionPane.showMessageDialog(null, " An error occured!! \n Try again later or contact your system admin for help."); close_loda(); } return response.toString(); } catch (Exception e) { JOptionPane.showMessageDialog(null, " An error occured!! \n Contact your system admin for help.", null, JOptionPane.WARNING_MESSAGE); close_loda(); return null; } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.otaupdater.DownloadsActivity.java
private void flashFiles(String[] files, boolean backup, boolean wipeCache, boolean wipeData) { try {/*from w w w .j a va 2 s .c om*/ Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); os.writeBytes("mkdir -p /cache/recovery/\n"); os.writeBytes("rm -f /cache/recovery/command\n"); os.writeBytes("rm -f /cache/recovery/extendedcommand\n"); os.writeBytes("echo 'boot-recovery' >> /cache/recovery/command\n"); //no official cwm for sony, so use extendedcommand. sony devices cannot use regular command file if (Build.MANUFACTURER.toLowerCase(Locale.US).contains("sony")) { if (backup) { os.writeBytes("echo 'backup_rom /sdcard/clockworkmod/backup/ota_" + new SimpleDateFormat("yyyy-MM-dd_HH.mm", Locale.US).format(new Date()) + "' >> /cache/recovery/extendedcommand\n"); } if (wipeData) { os.writeBytes("echo 'format(\"/data\");' >> /cache/recovery/extendedcommand\n"); } if (wipeCache) { os.writeBytes("echo 'format(\"/cache\");' >> /cache/recovery/extendedcommand\n"); } for (String file : files) { os.writeBytes("echo 'install_zip(\"" + file + "\");' >> /cache/recovery/extendedcommand\n"); } } else { if (backup) { os.writeBytes("echo '--nandroid' >> /cache/recovery/command\n"); } if (wipeData) { os.writeBytes("echo '--wipe_data' >> /cache/recovery/command\n"); } if (wipeCache) { os.writeBytes("echo '--wipe_cache' >> /cache/recovery/command\n"); } for (String file : files) { os.writeBytes("echo '--update_package=" + file + "' >> /cache/recovery/command\n"); } } String rebootCmd = PropUtils.getRebootCmd(); if (!rebootCmd.equals("$$NULL$$")) { os.writeBytes("sync\n"); if (rebootCmd.endsWith(".sh")) { os.writeBytes("sh " + rebootCmd + "\n"); } else { os.writeBytes(rebootCmd + "\n"); } } os.writeBytes("sync\n"); os.writeBytes("exit\n"); os.flush(); p.waitFor(); ((PowerManager) getSystemService(POWER_SERVICE)).reboot("recovery"); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.apteligent.ApteligentJavaClient.java
private HttpsURLConnection sendPostRequest(String endpoint, String params) throws IOException { // build conn object for POST request URL obj = new URL(endpoint); HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection(); conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()); conn.setDoOutput(true);//from w ww. ja va 2 s .c om conn.setDoInput(true); conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken()); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length)); conn.setRequestMethod("POST"); // Send post request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); return conn; }
From source file:org.belio.service.gateway.AirtelCharging.java
private String sendXmlOverPost(String url, String xml) { StringBuffer result = new StringBuffer(); try {// w w w .jav a2s .com Launcher.LOG.info("======================xml=============="); Launcher.LOG.info(xml.toString()); // String userPassword = "roamtech_KE:roamtech _KE!ibm123"; // URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1"); String userPassword = "" + networkproperties.getProperty("air_info_u") + ":" + networkproperties.getProperty("air_info_p"); URL url2 = new URL(url); // URLConnection urlc = url.openConnection(); URLConnection urlc = url2.openConnection(); HttpsURLConnection conn = (HttpsURLConnection) urlc; conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("SOAPAction", "run"); // urlc.setDoOutput(true); // urlc.setUseCaches(false); // urlc.setAllowUserInteraction(false); conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes())); conn.setRequestProperty("Content-Type", "text/xml"); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); // Write post data DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(xml); out.flush(); out.close(); BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuffer responseMessage = new StringBuffer(); while ((line = aiResult.readLine()) != null) { responseMessage.append(line); } System.out.println(responseMessage); //urlc.s("POST"); // urlc.setRequestProperty("SOAPAction", SOAP_ACTION); urlc.connect(); } catch (MalformedURLException ex) { Logger.getLogger(AirtelCharging.class .getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AirtelCharging.class .getName()).log(Level.SEVERE, null, ex); } return result.toString(); // try { // // String url = "https://selfsolve.apple.com/wcResults.do"; // HttpClient client = new DefaultHttpClient(); // HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1"); // // add header // post.setHeader("User-Agent", USER_AGENT); // post.setHeader("Content-type:", " text/xml"); // post.setHeader("charset", "utf-8"); // post.setHeader("Accept:", ",text/xml"); // post.setHeader("Cache-Control:", " no-cache"); // post.setHeader("Pragma:", " no-cache"); // post.setHeader("SOAPAction:", "run"); // post.setHeader("Content-length:", "xml"); // //// String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":" //// + networkproperties.getProperty("air_charge_p")).getBytes()); // String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes()); // // post.setHeader("Authorization", "Basic " + encoding); // // // post.setHeader("Authorization: Basic ", "base64_encode(credentials)"); // List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); // // urlParameters.add(new BasicNameValuePair("xml", xml)); // // System.out.println("\n============================ : " + url); // //// urlParameters.add(new BasicNameValuePair("srcCode", "")); //// urlParameters.add(new BasicNameValuePair("phone", "")); //// urlParameters.add(new BasicNameValuePair("contentId", "")); //// urlParameters.add(new BasicNameValuePair("itemName", "")); //// urlParameters.add(new BasicNameValuePair("contentDescription", "")); //// urlParameters.add(new BasicNameValuePair("actualPrice", "")); //// urlParameters.add(new BasicNameValuePair("contentMediaType", "")); //// urlParameters.add(new BasicNameValuePair("contentUrl", "")); // post.setEntity(new UrlEncodedFormEntity(urlParameters)); // // HttpResponse response = client.execute(post); // Launcher.LOG.info("\nSending 'POST' request to URL : " + url); // Launcher.LOG.info("Post parameters : " + post.getEntity()); // Launcher.LOG.info("Response Code : " // + response.getStatusLine().getStatusCode()); // // BufferedReader rd = new BufferedReader( // new InputStreamReader(response.getEntity().getContent())); // // String line = ""; // while ((line = rd.readLine()) != null) { // result.append(line); // } // // System.out.println(result.toString()); // } catch (UnsupportedEncodingException ex) { // Launcher.LOG.info(ex.getMessage()); // } catch (IOException ex) { // Launcher.LOG.info(ex.getMessage()); // } }
From source file:com.apteligent.ApteligentJavaClient.java
/*********************************************************************************************************************/ private Token auth(String email, String password) throws IOException { String urlParameters = "grant_type=password&username=" + email + "&password=" + password; URL obj = new URL(API_TOKEN); HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection(); conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()); conn.setDoOutput(true);/* ww w. j a v a 2s.c om*/ conn.setDoInput(true); //add request header String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes())); conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth)); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); conn.setRequestMethod("POST"); // Send post request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // read token JsonFactory jsonFactory = new JsonFactory(); JsonParser jp = jsonFactory.createParser(conn.getInputStream()); ObjectMapper mapper = getObjectMapper(); Token token = mapper.readValue(jp, Token.class); return token; }