List of usage examples for javax.net.ssl HttpsURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:org.wso2.carbon.sample.service.EventsManagerService.java
public String performPostCall(String requestURL, Map<String, String> postDataParams) throws HttpException, IOException { URL url;//from ww w.ja v a 2s . co m String response = ""; url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } else { response = ""; throw new HttpException(responseCode + ""); } return response; }
From source file:org.mule.modules.wechat.common.HttpsConnection.java
public Map<String, Object> post(String httpsURL, String json) throws Exception { // Setup connection String result = ""; URL url = new URL(httpsURL); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json; encoding=utf-8"); con.setDoOutput(true);/*from www. j ava 2s.c o m*/ OutputStream ops = con.getOutputStream(); ops.write(json.getBytes("UTF-8")); ops.flush(); ops.close(); // Call wechat InputStream ins = con.getInputStream(); InputStreamReader isr = new InputStreamReader(ins, "UTF-8"); BufferedReader in = new BufferedReader(isr); // Read result String inputLine; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { sb.append((new JSONObject(inputLine)).toString()); } result = sb.toString(); in.close(); // Convert JSON string to Map ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() { }); return map; }
From source file:org.georchestra.console.ReCaptchaV2.java
/** * * @param url// w w w .ja v a 2 s . com * @param privateKey * @param gRecaptchaResponse * * @return true if validaded on server side by google, false in case of error or if an exception occurs */ public boolean isValid(String url, String privateKey, String gRecaptchaResponse) { boolean isValid = false; try { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add request header con.setRequestMethod("POST"); String postParams = "secret=" + privateKey + "&response=" + gRecaptchaResponse; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); if (LOG.isDebugEnabled()) { int responseCode = con.getResponseCode(); LOG.debug("\nSending 'POST' request to URL : " + url); LOG.debug("Post parameters : " + postParams); LOG.debug("Response Code : " + responseCode); } // getResponse 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 LOG.debug(response.toString()); JSONObject captchaResponse; try { captchaResponse = new JSONObject(response.toString()); if (captchaResponse.getBoolean("success")) { isValid = true; } else { // Error in response LOG.info("The user response to recaptcha is not valid. The error message is '" + captchaResponse.getString("error-codes") + "' - see Error Code Reference at https://developers.google.com/recaptcha/docs/verify."); } } catch (JSONException e) { // Error in response LOG.error("Error while parsing ReCaptcha JSON response", e); } } catch (IOException e) { LOG.error("An error occured when trying to contact google captchaV2", e); } return isValid; }
From source file:Activities.java
private String addData(String endpoint) { String data = null;/*from w w w .j av a 2 s . c o m*/ try { // Construct request payload JSONObject attrObj = new JSONObject(); attrObj.put("name", "URL"); attrObj.put("value", "http://www.nvidia.com/game-giveaway"); JSONArray attrArray = new JSONArray(); attrArray.add(attrObj); TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); String dateAsISO = df.format(new Date()); // Required attributes JSONObject obj = new JSONObject(); obj.put("leadId", "1001"); obj.put("activityDate", dateAsISO); obj.put("activityTypeId", "1001"); obj.put("primaryAttributeValue", "Game Giveaway"); obj.put("attributes", attrArray); System.out.println(obj); // Make request URL url = new URL(endpoint); HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setAllowUserInteraction(false); urlConn.setDoOutput(true); urlConn.setRequestProperty("Content-type", "application/json"); urlConn.setRequestProperty("accept", "application/json"); urlConn.connect(); OutputStream os = urlConn.getOutputStream(); os.write(obj.toJSONString().getBytes()); os.close(); // Inspect response int responseCode = urlConn.getResponseCode(); if (responseCode == 200) { System.out.println("Status: 200"); InputStream inStream = urlConn.getInputStream(); data = convertStreamToString(inStream); System.out.println(data); } else { System.out.println(responseCode); data = "Status:" + responseCode; } } catch (MalformedURLException e) { System.out.println("URL not valid."); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); e.printStackTrace(); } return data; }
From source file:org.sakaiproject.contentreview.turnitin.util.TurnitinAPIUtil.java
public static InputStream callTurnitinReturnInputStream(String apiURL, Map<String, Object> parameters, String secretKey, int timeout, Proxy proxy, boolean isMultipart) throws TransientSubmissionException, SubmissionException { InputStream togo = null;//from ww w . jav a2 s .c o m StringBuilder apiDebugSB = new StringBuilder(); if (!parameters.containsKey("fid")) { throw new IllegalArgumentException("You must to include a fid in the parameters"); } //if (!parameters.containsKey("gmttime")) { parameters.put("gmtime", getGMTime()); //} /** * Some debug logging */ if (log.isDebugEnabled()) { Set<Entry<String, Object>> ets = parameters.entrySet(); Iterator<Entry<String, Object>> it = ets.iterator(); while (it.hasNext()) { Entry<String, Object> entr = it.next(); log.debug("Paramater entry: " + entr.getKey() + ": " + entr.getValue()); } } List<String> sortedkeys = new ArrayList<String>(); sortedkeys.addAll(parameters.keySet()); String md5 = buildTurnitinMD5(parameters, secretKey, sortedkeys); HttpsURLConnection connection; String boundary = ""; try { connection = fetchConnection(apiURL, timeout, proxy); connection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); if (isMultipart) { Random rand = new Random(); //make up a boundary that should be unique boundary = Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); } log.debug("HTTPS Connection made to Turnitin"); OutputStream outStream = connection.getOutputStream(); if (isMultipart) { if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append("Starting Multipart TII CALL:\n"); } for (int i = 0; i < sortedkeys.size(); i++) { if (parameters.get(sortedkeys.get(i)) instanceof ContentResource) { ContentResource resource = (ContentResource) parameters.get(sortedkeys.get(i)); outStream.write( ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"pdata\"; filename=\"" + resource.getId() + "\"\r\n" + "Content-Type: " + resource.getContentType() + "\r\ncontent-transfer-encoding: binary" + "\r\n\r\n").getBytes()); //TODO this loads the doc into memory rather use the stream method byte[] content = resource.getContent(); if (content == null) { throw new SubmissionException("zero length submission!"); } outStream.write(content); outStream.write("\r\n".getBytes("UTF-8")); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append(sortedkeys.get(i)); apiDebugSB.append(" = ContentHostingResource: "); apiDebugSB.append(resource.getId()); apiDebugSB.append("\n"); } } else { if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append(sortedkeys.get(i)); apiDebugSB.append(" = "); apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString()); apiDebugSB.append("\n"); } outStream.write(encodeParam(sortedkeys.get(i), parameters.get(sortedkeys.get(i)).toString(), boundary).getBytes()); } } outStream.write(encodeParam("md5", md5, boundary).getBytes()); outStream.write(("--" + boundary + "--").getBytes()); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append("md5 = "); apiDebugSB.append(md5); apiDebugSB.append("\n"); apiTraceLog.debug(apiDebugSB.toString()); } } else { writeBytesToOutputStream(outStream, sortedkeys.get(0), "=", parameters.get(sortedkeys.get(0)).toString()); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append("Starting TII CALL:\n"); apiDebugSB.append(sortedkeys.get(0)); apiDebugSB.append(" = "); apiDebugSB.append(parameters.get(sortedkeys.get(0)).toString()); apiDebugSB.append("\n"); } for (int i = 1; i < sortedkeys.size(); i++) { writeBytesToOutputStream(outStream, "&", sortedkeys.get(i), "=", parameters.get(sortedkeys.get(i)).toString()); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append(sortedkeys.get(i)); apiDebugSB.append(" = "); apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString()); apiDebugSB.append("\n"); } } writeBytesToOutputStream(outStream, "&md5=", md5); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append("md5 = "); apiDebugSB.append(md5); apiTraceLog.debug(apiDebugSB.toString()); } } outStream.close(); togo = connection.getInputStream(); } catch (IOException t) { log.error("IOException making turnitin call.", t); throw new TransientSubmissionException("IOException making turnitin call.", t); } catch (ServerOverloadException t) { throw new TransientSubmissionException("Unable to submit the content data from ContentHosting", t); } return togo; }
From source file:crossbear.convergence.ConvergenceConnector.java
/** * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host. * /* ww w. java 2 s .c o m*/ * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear. * * @param notary * The notary to contact * @param hostPort * The Hostname and port of the server on which the information about the certificate observations is desired. * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ private static String contactNotary(ConvergenceNotary notary, String hostPort) throws IOException, KeyManagementException, NoSuchAlgorithmException { // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)") String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29"; // Build the url to connect to based on the Notary and the certificate's host URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+")); // Open a HttpsURLConnection for that url HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); /* * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary. */ SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) }, new java.security.SecureRandom()); conn.setSSLSocketFactory(sc.getSocketFactory()); // Set the timeout during which the Notary has to reply conn.setConnectTimeout(3000); // POST the fake fingerprint to the Notary conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream(). InputStream is; if (conn.getResponseCode() >= 400) { is = conn.getErrorStream(); } else { // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ... is = conn.getInputStream(); } // Read the Notary's reply and store it String response = Message.inputStreamToString(is); // Close all opened streams wr.close(); // Return the Notary's reply return response; }
From source file:com.kaixin.connect.Util.java
/** * http/*www. ja v a 2 s .c o m*/ * * @param context * * @param requestURL * * @param httpMethod * GET POST * @param params * key-valuekeyvalueStringbyte[] * @param photos * key-value keyfilename * valueInputStreambyte[] * InputStreamopenUrl * @return JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, ""); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }
From source file:com.ds.kaixin.Util.java
/** * http// w ww. j a va 2s . c o m * * @param context * * @param requestURL * * @param httpMethod * GET POST * @param params * key-valuekeyvalueString * byte[] * @param photos * key-value keyfilename * valueInputStreambyte[] * InputStreamopenUrl * @return JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, ""); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }
From source file:org.jboss.aerogear.adm.TokenService.java
/** * Returns HttpsURLConnection that 'posts' the given payload to ADM. */// w ww .ja v a 2s . c o m private HttpsURLConnection post(final String payload) throws Exception { final HttpsURLConnection conn = getHttpsURLConnection(); conn.setDoOutput(true); conn.setUseCaches(false); // Set the content type . conn.setRequestProperty("content-type", APPLICATION_X_WWW_FORM_URLENCODED); conn.setRequestProperty("charset", UTF_8); conn.setRequestMethod("POST"); OutputStream out = null; final byte[] bytes = payload.getBytes(UTF_8_CHARSET); try { out = conn.getOutputStream(); out.write(bytes); out.flush(); } finally { // in case something blows up, while writing // the payload, we wanna close the stream: if (out != null) { out.close(); } } return conn; }
From source file:com.fastbootmobile.twofactorauthdemo.MainActivity.java
protected void registerWithBackend() { final SharedPreferences pref = this.getSharedPreferences(OwnPushClient.PREF_PUSH, Context.MODE_PRIVATE); Thread httpThread = new Thread(new Runnable() { private String TAG = "httpThread"; private String ENDPOINT = "https://otp.demo.ownpush.com/push/register"; @Override//www .j a v a 2s .com public void run() { URL urlObj; try { urlObj = new URL(ENDPOINT); String install_id = pref.getString(OwnPushClient.PREF_PUBLIC_KEY, null); if (install_id == null) { return; } String mPostData = "push_id=" + install_id; HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); con.setRequestProperty("Accept", "*/*"); con.setDoInput(true); con.setRequestMethod("POST"); con.getOutputStream().write(mPostData.getBytes()); con.connect(); int http_status = con.getResponseCode(); if (http_status != 200) { Log.e(TAG, "ERROR IN HTTP REPONSE : " + http_status); return; } InputStream stream; stream = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String data = sb.toString(); if (data.contains("device_uid")) { JSONObject json = new JSONObject(data); String device_id = json.getString("device_uid"); pref.edit().putString("device_uid", device_id).commit(); Log.d(TAG, "GOT DEVICE UID OF " + device_id); mHandler.post(new Runnable() { @Override public void run() { updateUI(); } }); } } catch (Exception e) { e.printStackTrace(); } } }); httpThread.start(); }