List of usage examples for javax.net.ssl HttpsURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:org.openadaptor.util.PropertiesPoster.java
/** * Utility method which will attempt to POST the supplied properties information to the supplied URL. * // ww w . java 2 s .c o m * This method currently contains an all trusting trust manager for use with https. This will be replaced with a more * secure trust manager which will use a cert store. * * @param registrationURL * @param properties * @throws Exception */ protected static void syncPostHttp(String registrationURL, Properties properties) throws Exception { URL url = new URL(registrationURL); String postData = generatePOSTData(properties); log.debug("Protocol: " + url.getProtocol()); if (url.getProtocol().equals("https")) { // https connection // TODO: Replace this all trusting manager with one that uses a cert store // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection secureConnection = null; HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); secureConnection = (HttpsURLConnection) url.openConnection(); secureConnection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(secureConnection.getOutputStream()); writer.write(postData); writer.flush(); int responseCode = secureConnection.getResponseCode(); if (HttpsURLConnection.HTTP_OK != responseCode) { log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:" + secureConnection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: " + generateString(properties)); } BufferedReader br = new BufferedReader(new InputStreamReader(secureConnection.getInputStream())); String line; while ((line = br.readLine()) != null) { log.debug("Returned data: " + line); } writer.close(); br.close(); } else { // Normal http connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(postData); writer.flush(); int responseCode = connection.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:" + connection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: " + generateString(properties)); } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = br.readLine()) != null) { log.debug("Returned data: " + line); } writer.close(); br.close(); } }
From source file:tk.egsf.ddns.JSON_helper.java
public static String postToUrl(String URL, String Auth, JSONObject post) { String ret = ""; String https_url = URL; URL url;/*from w w w .j a v a 2s . c om*/ try { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); url = new URL(https_url); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("Authorization", Auth); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestMethod("POST"); con.setDoOutput(true); con.connect(); // Send post System.out.println(post.toString()); byte[] outputBytes = post.toString().getBytes("UTF-8"); OutputStream os = con.getOutputStream(); os.write(outputBytes); os.close(); // get response BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input; while ((input = br.readLine()) != null) { ret += input; } br.close(); System.out.println(ret); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { // e.printStackTrace(); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } return ret; }
From source file:com.ibm.mobilefirst.mobileedge.utils.RequestUtils.java
public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData, List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException { URL url = new URL("https://medge.mybluemix.net/alg/train"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(5000);//from ww w. jav a 2s. c o m conn.setConnectTimeout(10000); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); JSONObject jsonToSend = createTrainBodyJSON(name, uuid, accelerometerData, gyroscopeData); OutputStream outputStream = conn.getOutputStream(); DataOutputStream wr = new DataOutputStream(outputStream); wr.writeBytes(jsonToSend.toString()); wr.flush(); wr.close(); outputStream.close(); String response = ""; int responseCode = conn.getResponseCode(); //Log.e("BBB2","" + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } else { response = "{}"; } handleResponse(response, requestResult); }
From source file:com.tohours.imo.util.TohoursUtils.java
/** * //from w w w. j av a 2 s. c om * @param path * @param charsetName * @param param * @return * @throws IOException */ public static String httpsPost(String path, String param, String charsetName) throws IOException { String rv = null; URL url = null; HttpsURLConnection conn = null; InputStream input = null; try { url = new URL(path); conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "plain/text"); conn.setRequestProperty("User-Agent", "Tohours Project"); OutputStream os = conn.getOutputStream(); os.write(param.getBytes(charsetName)); os.flush(); os.close(); input = conn.getInputStream(); rv = TohoursUtils.inputStream2String(input, charsetName); } finally { if (input != null) { input.close(); } } return rv; }
From source file:core.Web.java
public static JSONObject httpsRequest(URL url, Map<String, String> properties, JSONObject message) { // System.out.println(url); try {//from w w w .j a va 2s. c o m // Create connection HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); //connection.addRequestProperty("Authorization", API_KEY); // Set properties if needed if (properties != null && !properties.isEmpty()) { properties.forEach(connection::setRequestProperty); } // Post message if (message != null) { // Maybe somewhere connection.setDoOutput(true); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream()))) { writer.write(message.toString()); } } // Establish connection connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode != 200) { throw new RuntimeException("Response code was not 200. Detected response was " + responseCode); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; String content = ""; while ((line = reader.readLine()) != null) { content += line; } return new JSONObject(content); } } catch (IOException ex) { Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.webarch.common.net.http.HttpService.java
/** * ?Https/* ww w.ja v a2 s. c o m*/ * * @param requestUrl ? * @param requestMethod ? * @param trustManagers ?? * @param outputJson ? * @return */ public static String doHttpsRequest(String requestUrl, String requestMethod, TrustManager[] trustManagers, String outputJson) { String result = null; try { StringBuffer buffer = new StringBuffer(); // SSLContext?? SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, trustManagers, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET); httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET); // ?GET/POST httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // ???? if (null != outputJson) { OutputStream outputStream = httpUrlConn.getOutputStream(); //?? outputStream.write(outputJson.getBytes(DEFAULT_CHARSET)); outputStream.close(); } // ??? InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } result = buffer.toString(); bufferedReader.close(); inputStreamReader.close(); // ? inputStream.close(); httpUrlConn.disconnect(); } catch (ConnectException ce) { logger.error("Weixin server connection timed out.", ce); } catch (Exception e) { logger.error("https request error:", e); } finally { return result; } }
From source file:dictinsight.utils.io.HttpUtils.java
/** * https??post//from w w w . j a v a 2s. c om * @param url * @param param * @return post? */ public static String httpsPostData(String url, String param) { class DefaultTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } BufferedOutputStream brOutStream = null; BufferedReader reader = null; try { SSLContext context = SSLContext.getInstance("SSL"); context.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection(); connection.setSSLSocketFactory(context.getSocketFactory()); connection.setRequestMethod("POST"); connection.setRequestProperty("Proxy-Connection", "Keep-Alive"); connection.setDoInput(true); connection.setDoOutput(true); connection.setConnectTimeout(1000 * 15); brOutStream = new BufferedOutputStream(connection.getOutputStream()); brOutStream.write(param.getBytes()); brOutStream.flush(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String responseContent = ""; String line = reader.readLine(); while (line != null) { responseContent += line; line = reader.readLine(); } return responseContent; } catch (Exception e) { e.printStackTrace(); } finally { try { if (brOutStream != null) brOutStream.close(); if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
From source file:ro.fortsoft.matilda.util.RecaptchaUtils.java
public static boolean verify(String recaptchaResponse, String secret) { if (StringUtils.isNullOrEmpty(recaptchaResponse)) { return false; }/* ww w. j a v a 2s . 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.illusionaryone.GoogleURLShortenerAPIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress, String longURL) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;/*from w w w.j ava 2 s. co m*/ HttpsURLConnection urlConn; String jsonRequest = ""; String jsonText = ""; try { jsonRequest = "{ 'longUrl': '" + longURL + "'}"; byte[] postRequest = jsonRequest.getBytes("UTF-8"); urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.addRequestProperty("Content-Length", String.valueOf(postRequest.length)); urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json"); urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); urlConn.connect(); urlConn.getOutputStream().write(postRequest); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (UnsupportedEncodingException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "UnsupportedEncodingException", ex.getMessage(), jsonText); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } } return (jsonResult); }
From source file:org.transitime.custom.missionBay.SfmtaApiCaller.java
/** * Posts the JSON string to the URL. For either the telemetry or the stop * command./* w w w . java2 s .c o m*/ * * @param baseUrl * @param jsonStr * @return True if successfully posted the data */ private static boolean post(String baseUrl, String jsonStr) { try { // Create the connection URL url = new URL(baseUrl); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); // Set parameters for the connection con.setRequestMethod("POST"); con.setRequestProperty("content-type", "application/json"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); // API now uses basic authentication String authString = login.getValue() + ":" + password.getValue(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); con.setRequestProperty("Authorization", "Basic " + authStringEnc); // Set the timeout so don't wait forever (unless timeout is set to 0) int timeoutMsec = timeout.getValue(); con.setConnectTimeout(timeoutMsec); con.setReadTimeout(timeoutMsec); // Write the json data to the connection DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(jsonStr); wr.flush(); wr.close(); // Get the response int responseCode = con.getResponseCode(); // If wasn't successful then log the response so can debug if (responseCode != 200) { String responseStr = ""; if (responseCode != 500) { // Response code indicates there was a problem so get the // reply in case API returned useful error message InputStream inputStream = con.getErrorStream(); if (inputStream != null) { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); responseStr = response.toString(); } } // Lot that response code indicates there was a problem logger.error( "Bad HTTP response {} when writing data to SFMTA " + "API. Response text=\"{}\" URL={} json=\n{}", responseCode, responseStr, baseUrl, jsonStr); } // Done so disconnect just for the heck of it con.disconnect(); // Return whether was successful return responseCode == 200; } catch (IOException e) { logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(), baseUrl, jsonStr); // Return that was unsuccessful return false; } }