List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.example.jarida.http.AsyncConnection.java
@Override public String doInBackground(String... params) { final String method = params[0]; final String urlString = params[1]; final StringBuilder builder = new StringBuilder(); try {/* ww w . jav a2 s . c om*/ final URL url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); if (method.equals(METHOD_POST)) { final String urlParams = params[2]; conn.setRequestProperty(HTTP.CONTENT_LEN, "" + Integer.toString(urlParams.getBytes().length)); System.out.println(urlParams); // Send request final DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(urlParams); wr.flush(); wr.close(); } // Get Response final InputStream is = conn.getInputStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { builder.append(line); } rd.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
From source file:com.jyzn.wifi.validate.platforminterface.SmsInterfaceImpl.java
@Override public Map HttpSendSms(String postUrl, String postData) { String result = ""; Map resultMap = Maps.newHashMap(); try {/* w w w .j a va 2 s . com*/ //??POST URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", "" + postData.length()); try { OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.write(postData); out.flush();//? } catch (IOException e) { } //??? if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println("connect failed!"); resultMap.put("status", "fail"); //return "fail"; } //?? String line; try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) { while ((line = in.readLine()) != null) { result += line + "\n"; } } resultMap.put("status", "sucess"); resultMap.put("result", result); } catch (IOException e) { e.printStackTrace(System.out); } return resultMap; }
From source file:com.amazon.alexa.avs.auth.companionapp.OAuth2ClientForPkce.java
JsonObject postRequest(HttpURLConnection connection, String data) throws IOException { int responseCode = -1; InputStream error = null;/* ww w . j a v a 2s . c o m*/ InputStream response = null; DataOutputStream outputStream = null; connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(data.getBytes(StandardCharsets.UTF_8)); outputStream.flush(); outputStream.close(); responseCode = connection.getResponseCode(); try { response = connection.getInputStream(); JsonReader reader = Json.createReader(new InputStreamReader(response, StandardCharsets.UTF_8)); return reader.readObject(); } catch (IOException ioException) { error = connection.getErrorStream(); if (error != null) { LWAException lwaException = new LWAException(IOUtils.toString(error), responseCode); throw lwaException; } else { throw ioException; } } finally { IOUtils.closeQuietly(error); IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(response); } }
From source file:com.example.llh_pc.it_support.gcm.RegistrationIntentService.java
private void sendMessage() { try {//from w ww . jav a2s . co m // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", "eNdGvapH6Bw:APA91bFwqyXhYWvMCDTuYDUAOTLpJqIFr_gC5BFmnm7zUE9Hljjx0it9aKMeVrqJz5RqxiOo6WflH7HdQg-SAngyqRPeE94rEf2H9gL2cGxJIfVrNtTu4DF1_P9e7q6xnVVX5G7xd8QW"); // Where to send GCM message. // if (args.length > 1 && args[1] != null) { // jGcmData.put("to", args[1].trim()); // } else { // jGcmData.put("to", "/topics/global"); // } jGcmData.put("to", "eNdGvapH6Bw:APA91bFwqyXhYWvMCDTuYDUAOTLpJqIFr_gC5BFmnm7zUE9Hljjx0it9aKMeVrqJz5RqxiOo6WflH7HdQg-SAngyqRPeE94rEf2H9gL2cGxJIfVrNtTu4DF1_P9e7q6xnVVX5G7xd8QW"); // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + "AIzaSyCNdYvJwpxD7qKY1_E-gRPh9_w59tnSV34"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:Main.java
@SuppressWarnings("resource") public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) { Logd(TAG, "Starting post..."); String html = ""; Boolean cont = true;//from ww w . j a v a 2 s .co m URL url = null; try { url = new URL(targetUrl); } catch (MalformedURLException e) { Log.e(TAG, "Invalid url: " + targetUrl); cont = false; throw new IllegalArgumentException("Invalid url: " + targetUrl); } if (cont) { if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) { HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); } else { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } } }; // Install the all-trusting trust manager SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (NoSuchAlgorithmException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } catch (KeyManagementException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } } Logd(TAG, "Filename: " + file); Logd(TAG, "URL: " + targetUrl); HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = file; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024; try { connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header) //connection.setChunkedStreamingMode(1024); // Enable POST method connection.setRequestMethod("POST"); setBasicAuthentication(connection, url); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); //outputStream.writeBytes(twoHyphens + boundary + lineEnd); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\"" + lineEnd + lineEnd); outputStream.write(param.getValue().getBytes("UTF-8")); outputStream.writeBytes(lineEnd); } String connstr = null; if (!file.equals("")) { FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); Logd(TAG, "File length: " + bytesAvailable); try { while (bytesRead > 0) { try { outputStream.write(buffer, 0, bufferSize); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); fileInputStream.close(); } else if (data != null) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = data.length; Logd(TAG, "File length: " + bytesAvailable); try { outputStream.write(data, 0, data.length); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Logd(TAG, "Server Response Code " + serverResponseCode); Logd(TAG, "Server Response Message: " + serverResponseMessage); if (serverResponseCode == 200) { InputStreamReader in = new InputStreamReader(connection.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } outputStream.flush(); outputStream.close(); outputStream = null; } catch (Exception ex) { // Exception handling html = "Error: Unknown error"; Logd(TAG, "Send file Exception: " + ex.getMessage()); } } if (html.startsWith("success:")) Logd(TAG, "Server returned: success:HIDDEN"); else Logd(TAG, "Server returned: " + html); return html; }
From source file:org.csware.ee.utils.Tools.java
public static String GetDataByPost(String httpUrl, String parMap) { try {/*from w w w . j av a 2 s. c o m*/ URL url = new URL(httpUrl);// HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); // ? connection.setRequestProperty("Accept", "application/json"); // ?? connection.setRequestProperty("Content-Type", "application/json"); // ???? connection.connect(); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8? out.append(parMap); out.flush(); out.close(); // ?? int length = (int) connection.getContentLength();// ? InputStream is = connection.getInputStream(); if (length != -1) { byte[] data = new byte[length]; byte[] temp = new byte[1024]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0) { System.arraycopy(temp, 0, data, destPos, readLen); destPos += readLen; } String result = new String(data, "UTF-8"); // utf-8? return result; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("aa: " + e.getMessage()); } return "error"; // ? }
From source file:br.bireme.accounts.Authentication.java
public JSONObject getUser(final String user, final String password) throws IOException, ParseException { if (user == null) { throw new NullPointerException("user"); }/*from w w w. j a v a 2s.c o m*/ if (password == null) { throw new NullPointerException("password"); } final JSONObject parameters = new JSONObject(); parameters.put("username", user); parameters.put("password", password); parameters.put("service", SERVICE_NAME); parameters.put("format", "json"); //final URL url = new URL("http", host, port, DEFAULT_PATH); final URL url = new URL("http://" + host + DEFAULT_PATH); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); final StringBuilder builder = new StringBuilder(); final BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream(), "UTF-8")); //final String message = parameters.toJSONString(); //System.out.println(message); writer.write(parameters.toJSONString()); writer.newLine(); writer.close(); final int respCode = connection.getResponseCode(); final boolean respCodeOk = (respCode == 200); final BufferedReader reader; if (respCodeOk) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); } else { reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); } while (true) { final String line = reader.readLine(); if (line == null) { break; } builder.append(line); builder.append("\n"); } reader.close(); if (!respCodeOk && (respCode != 401)) { throw new IOException(builder.toString()); } return (JSONObject) new JSONParser().parse(builder.toString()); }
From source file:com.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 va2s . c o m * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @SuppressWarnings("deprecation") 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.bpd.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 ww w . j av a 2 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; // Try to get filename key String filename = params.getString("filename"); // If found if (filename != null) { // Remove from params params.remove("filename"); } 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=\"" + ((filename != null) ? 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.kinvey.business_logic.collection_access.MongoRequest.java
private HttpResponse makeRequest() throws CollectionAccessException { KinveyAuthCredentials authCredentials = KinveyAuthCredentials.getInstance(); try {//w ww . j ava2 s .c o m String encodedUrl = this.protocol + "://" + this.baseUrl + "/" + authCredentials.getAppId() + "/" + this.collection.collectionName + "/" + this.collectionOperation.getEndPoint(); String userPass = authCredentials.getAppId() + ":" + authCredentials.getMasterSecret(); String authString = "Basic " + new String(Base64.encode(userPass), "UTF-8"); URL url = new URL(encodedUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", authString); String input = buildBody(); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String tmpOutput; String contentBody = ""; while ((tmpOutput = br.readLine()) != null) { contentBody += tmpOutput; } conn.disconnect(); HttpResponse response = new HttpResponse(contentBody); return response; } catch (IOException e) { throw new CollectionAccessException(e); } }