List of usage examples for javax.net.ssl HttpsURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java
private void login() { String url = null;/*from ww w . j a v a 2s.com*/ try { //login url = ZONKY_URL + "oauth/token"; String urlParameters = "username=" + userName + "&password=" + password + "&grant_type=password&scope=SCOPE_APP_WEB"; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); setupConnectionDefaults(connection); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); connection.setRequestProperty("Authorization", "Basic d2ViOndlYg=="); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } String line = readResponse(connection); ZonkyTokenResponse response = gson.fromJson(line, ZonkyTokenResponse.class); token = response.getAccessToken(); refreshToken = response.getRefreshToken(); if (!token.isEmpty()) { logger.info("Successfully logged in to Zonky!"); } } catch (MalformedURLException e) { logger.error("The URL '{}' is malformed", url, e); } catch (Exception e) { logger.error("Cannot get Zonky login token", e); } }
From source file:de.escidoc.core.test.sb.HttpRequester.java
/** * Sends request with given method and given body to given URI and returns result as String. * * @param resource String resource//from w w w.ja v a2 s. c om * @param method String method * @param body String body * @return String response * @throws Exception e */ private String requestSsl(final String resource, final String method, final String body) throws Exception { URL url; InputStream is = null; StringBuffer response = new StringBuffer(); // Open Connection to given resource url = new URL(domain + resource); TrustManager[] tm = { new RelaxedX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, tm, new java.security.SecureRandom()); SSLSocketFactory sslSF = sslContext.getSocketFactory(); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(sslSF); // Set Basic-Authentication Header if (securityHandle != null && !securityHandle.equals("")) { String encoding = new String(Base64.encodeBase64(securityHandle.getBytes(ClientBase.DEFAULT_CHARSET))); con.setRequestProperty("Authorization", "Basic " + encoding); } // Set request-method and timeout con.setRequestMethod(method.toUpperCase(Locale.ENGLISH)); con.setReadTimeout(TIMEOUT); // If PUT or POST, write given body in Output-Stream if ((method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) && body != null) { con.setDoOutput(true); OutputStream out = con.getOutputStream(); out.write(body.getBytes(ClientBase.DEFAULT_CHARSET)); out.flush(); out.close(); } // Request is = con.getInputStream(); // Read response String currentLine = null; BufferedReader br = new BufferedReader(new InputStreamReader(is)); while ((currentLine = br.readLine()) != null) { response.append(currentLine + "\n"); } is.close(); return response.toString(); }
From source file:com.dao.ShopThread.java
private void pay(String payurl) { LogUtil.debugPrintf("----------->"); try {/*from www .ja v a 2 s .c om*/ String postParams = getPayDynamicParams(payurl); HttpsURLConnection loginConn = getHttpSConn(payurl, "POST", Integer.toString(postParams.length())); if (null != this.cookies) { loginConn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies)); } LogUtil.debugPrintf("HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + payurl); LogUtil.debugPrintf("Post parameters :" + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("conn.getHeaderFields():" + header); BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(2000); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String payresponse = response.toString(); LogUtil.debugPrintf("payresponse:" + payresponse); List<String> cookie = header.get("Set-Cookie"); String loginInfo; if (responseCode != 302) { LogUtil.debugPrintf("----------->"); loginInfo = ""; } else { LogUtil.debugPrintf("?----------->"); if (null != cookie && cookie.size() > 0) { LogUtil.debugPrintf("cookie====" + cookie); setCookies(cookie); } loginInfo = "?"; } LogUtil.webPrintf(loginInfo); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.aankor.animenforadio.api.WebsiteGate.java
private JSONObject request(EnumSet<Subscription> subscriptions) throws IOException, JSONException { // fetchCookies(); // TODO: fetch peice by piece URL url = new URL("https://www.animenfo.com/radio/index.php?t=" + (new Date()).getTime()); // URL url = new URL("http://192.168.0.2:12345/"); String body = "{\"ajaxcombine\":true,\"pages\":[{\"uid\":\"nowplaying\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"playing\"}}" + ",{\"uid\":\"queue\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"queue\"}},{\"uid\":\"recent\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"recent\"}}]}"; HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Accept-Encoding", "gzip, deflate"); con.setRequestProperty("Content-Type", "application/json"); if (!phpSessID.equals("")) con.setRequestProperty("Cookie", "PHPSESSID=" + phpSessID); con.setRequestProperty("Host", "www.animenfo.com"); con.setRequestProperty("Referer", "https://www.animenfo.com/radio/nowplaying.php"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.1.0"); // con.setUseCaches (false); con.setDoInput(true);/*from w w w . j a va 2s . com*/ con.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); // updateCookies(con); return new JSONObject(response.toString()); }
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);/*w ww . ja va 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; }
From source file:no.digipost.android.api.ApiAccess.java
public String postput(Context context, final int httpType, final String uri, final StringEntity json) throws DigipostClientException, DigipostApiException, DigipostAuthenticationException { HttpsURLConnection httpsClient; InputStream result = null;/*from www .ja v a 2 s. c om*/ try { URL url = new URL(uri); httpsClient = (HttpsURLConnection) url.openConnection(); if (httpType == POST) { httpsClient.setRequestMethod("POST"); } else if (httpType == PUT) { httpsClient.setRequestMethod("PUT"); } httpsClient.setRequestProperty(ApiConstants.CONTENT_TYPE, ApiConstants.APPLICATION_VND_DIGIPOST_V2_JSON); httpsClient.setRequestProperty(ApiConstants.ACCEPT, ApiConstants.APPLICATION_VND_DIGIPOST_V2_JSON); httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION, ApiConstants.BEARER + TokenStore.getAccess()); OutputStream outputStream; outputStream = new BufferedOutputStream(httpsClient.getOutputStream()); if (json != null) { json.writeTo(outputStream); } outputStream.flush(); int statusCode = httpsClient.getResponseCode(); try { NetworkUtilities.checkHttpStatusCode(context, statusCode); } catch (DigipostInvalidTokenException e) { OAuth.updateAccessTokenWithRefreshToken(context); return postput(context, httpType, uri, json); } if (statusCode == NetworkUtilities.HTTP_STATUS_NO_CONTENT) { return NetworkUtilities.SUCCESS_NO_CONTENT; } try { result = httpsClient.getInputStream(); } catch (IllegalStateException e) { Log.e(TAG, e.getMessage()); } } catch (IOException e) { throw new DigipostClientException(context.getString(R.string.error_your_network)); } return JSONUtilities.getJsonStringFromInputStream(result); }
From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java
public String[] callPostAndPut(String stringUrl, String body, String method) { try {/* w ww. j a v a 2s . c o m*/ // Setup connection URL url = new URL(stringUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(method.toUpperCase()); conn.setDoInput(true); // This is important to get the connection to use our trusted // certificate conn.setSSLSocketFactory(sslFactory); addHTTPBasicAuthProperty(conn); conn.setConnectTimeout(timeOut); // bug fixing for SSL error, this is a temporary fix, need to find a // long term one conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); log.error("body" + body); out.write(body); out.close(); conn.connect(); String result = ""; int code = conn.getResponseCode(); if (code == 201) { result = "Saved succefully"; } else { result = "Not Saved"; } conn.disconnect(); return new String[] { code + "", result }; } catch (MalformedURLException e) { e.printStackTrace(); log.error("MalformedURLException while callPostAndPut " + e.getMessage()); return new String[] { 400 + "", e.getMessage() }; } catch (IOException e) { e.printStackTrace(); log.error("IOException while callPostAndPut " + e.getMessage()); return new String[] { 600 + "", e.getMessage() }; } }
From source file:org.openhab.binding.unifi.internal.UnifiBinding.java
private boolean login() { String url = null;// ww w. j a va 2 s .c o m try { url = getControllerUrl("api/login"); String urlParameters = "{'username':'" + username + "','password':'" + password + "'}"; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Referer", getControllerUrl("login")); connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); connection.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } //get cookie cookies.clear(); String headerName; for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) { if (headerName.equals("Set-Cookie")) { cookies.add(connection.getHeaderField(i)); } } InputStream response = connection.getInputStream(); String line = readResponse(response); logger.debug("Unifi response: " + line); return checkResponse(line); } catch (MalformedURLException e) { logger.error("The URL '" + url + "' is malformed: " + e.toString()); } catch (Exception e) { logger.error("Cannot get Ubiquiti Unifi login cookie: " + e.toString()); } return false; }
From source file:tangocard.sdk.service.ServiceProxy.java
/** * Post request.// ww w . ja v a2 s . c o m * * @return true, if successful * @throws Exception the exception */ protected String postRequest() throws Exception { if (null == this._path) { throw new TangoCardSdkException("Member variable '_path' is null."); } String responseJsonEncoded = null; URL url = null; HttpsURLConnection connection = null; try { url = new URL(this._path); } catch (MalformedURLException e) { throw new TangoCardSdkException("MalformedURLException", e); } if (this.mapRequest()) { try { // connect to the server over HTTPS and submit the payload connection = (HttpsURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-length", String.valueOf(this._str_request_json.length())); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); // open up the output stream of the connection DataOutputStream output = new DataOutputStream(connection.getOutputStream()); output.write(this._str_request_json.getBytes()); } catch (Exception e) { throw new TangoCardSdkException(String.format("Problems executing request: %s: '%s'", e.getClass().toString(), e.getMessage()), e); } try { // now read the input stream until it is closed, line by line adding to the response InputStream inputstream = connection.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); StringBuffer response = new StringBuffer(); String line = null; while ((line = bufferedreader.readLine()) != null) { response.append(line); } responseJsonEncoded = response.toString(); } catch (Exception e) { throw new TangoCardSdkException(String.format("Problems reading response: %s: '%s'", e.getClass().toString(), e.getMessage()), e); } } return responseJsonEncoded; }
From source file:org.belio.service.gateway.AirtelCharging.java
private String sendXmlOverPost(String url, String xml) { StringBuffer result = new StringBuffer(); try {// w w w .j av a2s . c o m 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()); // } }