List of usage examples for javax.net.ssl HttpsURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java
/** * Send REST call//from w ww . j av a2s.co m */ private String sendRESTCall(String url, String urlParameters, String formParameters, String httpMethod) { String line; StringBuilder responseString = new StringBuilder(); HttpsURLConnection connection = null; try { setHttpsClientCert( "/media/sf_SharedFoldersToVBox/is-connectors/wikid/wikid-authenticator/org.wso2.carbon.identity.authenticator/src/main/resources/localhostWiKID", "shakila"); SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); URL wikidEP = new URL(url + urlParameters); connection = (HttpsURLConnection) wikidEP.openConnection(); connection.setSSLSocketFactory(sslsocketfactory); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod(httpMethod); connection.setRequestProperty(WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE, WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE_XWFUE); if (httpMethod.toUpperCase().equals(WiKIDAuthenticatorConstants.HTTP_POST)) { OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), WiKIDAuthenticatorConstants.CHARSET); writer.write(formParameters); writer.close(); } if (connection.getResponseCode() == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = br.readLine()) != null) { responseString.append(line); } br.close(); } else { return WiKIDAuthenticatorConstants.FAILED + WiKIDAuthenticatorConstants.REQUEST_FAILED; } } catch (ProtocolException e) { if (log.isDebugEnabled()) { log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage()); } return WiKIDAuthenticatorConstants.FAILED + e.getMessage(); } catch (MalformedURLException e) { if (log.isDebugEnabled()) { log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage()); } return WiKIDAuthenticatorConstants.FAILED + e.getMessage(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage()); } return WiKIDAuthenticatorConstants.FAILED + e.getMessage(); } finally { connection.disconnect(); } return responseString.toString(); }
From source file:com.mb.ext.web.controller.UserController.java
/** * //from w w w .j ava 2s .com * get news * */ @RequestMapping(value = "/pay", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public ResultDTO pay(@RequestBody PayDTO payDTO, HttpServletRequest request) { ResultDTO resultDTO = new ResultDTO(); PayRequest payRequest = new PayRequest(); payRequest.setAppid(WechatConstants.APPID_VALUE); payRequest.setMch_id(WechatConstants.MERCHANT_ID); payRequest.setNonce_str(RandomStringUtils.randomAlphanumeric(32)); payRequest.setOut_trade_no(payDTO.getOut_trade_no()); try { OrderDTO orderDTO = userService.getOrderByNumber(payDTO.getOut_trade_no()); String productName = orderDTO.getProductName(); BigDecimal amount = orderDTO.getPreAmount(); payRequest.setBody(productName); payRequest.setTotal_fee(amount.multiply(new BigDecimal(100)).intValue()); payRequest.setSpbill_create_ip(request.getRemoteAddr()); payRequest.setNotify_url(WechatConstants.NOTIFY_URL); payRequest.setTrade_type("APP"); payRequest.setAttach("ZHONGHUANBO"); } catch (Exception e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } payRequest.setSign(getSign(payRequest)); //xml XStream xstreamRes = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // CDATA boolean cdata = true; @SuppressWarnings("rawtypes") public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); XStream xstreamReq = new XStream(new XppDriver() /*{ public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // CDATA boolean cdata = true; @SuppressWarnings("rawtypes") public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }*/); xstreamReq.alias("xml", payRequest.getClass()); String requestXML = xstreamReq.toXML(payRequest).replace("\n", "").replace("__", "_"); try { requestXML = new String(requestXML.getBytes("utf-8"), "iso-8859-1"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // BufferedReader reader = null; InputStream is = null; DataOutputStream out = null; StringBuffer sbf = new StringBuffer(); String wechatResponseStr = ""; try { URL url = new URL(WechatConstants.UNIFIED_ORDER_URL); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(requestXML); out.flush(); is = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String strRead = null; while ((strRead = reader.readLine()) != null) { sbf.append(strRead); sbf.append("\r\n"); } wechatResponseStr = sbf.toString(); } catch (Exception e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } finally { try { reader.close(); is.close(); out.close(); } catch (IOException e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } } //? xstreamRes.alias("xml", PayResponse.class); PayResponse payResponse = (PayResponse) xstreamRes.fromXML(wechatResponseStr); //MOCK MODE /*PayResponse payResponse = new PayResponse(); payResponse.setPrepay_id("WX123456789009876543211234567890"); payResponse.setMch_id("6749328409382943"); payResponse.setNonce_str("764932874987392"); payResponse.setTrade_type("APP"); payResponse.setReturn_code("SUCCESS"); payResponse.setResult_code("SUCCESS");*/ if ("SUCCESS".equals(payResponse.getReturn_code()) && "SUCCESS".equals(payResponse.getResult_code())) { payDTO.setMch_id(payResponse.getMch_id()); payDTO.setNonce_str(payResponse.getNonce_str()); payDTO.setPrepay_id(payResponse.getPrepay_id()); payDTO.setTrade_type(payResponse.getTrade_type()); payDTO.setTimestamp(String.valueOf(System.currentTimeMillis() / 1000)); payDTO.setSign(getSignForClient(payDTO)); resultDTO.setBody(payDTO); resultDTO.setCode("0"); resultDTO.setMessage("??"); } else { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } return resultDTO; }
From source file:com.citrus.mobile.RESTclient.java
public JSONObject makeWithdrawRequest(String accessToken, double amount, String currency, String owner, String accountNumber, String ifscCode) { HttpsURLConnection conn; DataOutputStream wr = null;/*ww w . ja v a2s.c o m*/ JSONObject txnDetails = null; BufferedReader in = null; try { String url = urls.getString(base_url) + urls.getString(type); conn = (HttpsURLConnection) new URL(url).openConnection(); //add reuqest header conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + accessToken); StringBuffer buff = new StringBuffer("amount="); buff.append(amount); buff.append("¤cy="); buff.append(currency); buff.append("&owner="); buff.append(owner); buff.append("&account="); buff.append(accountNumber); buff.append("&ifsc="); buff.append(ifscCode); conn.setDoOutput(true); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(buff.toString()); wr.flush(); int responseCode = conn.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + buff.toString()); System.out.println("Response Code : " + responseCode); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } txnDetails = new JSONObject(response.toString()); } catch (JSONException exception) { exception.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } try { if (wr != null) { wr.close(); } } catch (IOException e) { e.printStackTrace(); } } return txnDetails; }
From source file:com.gloriouseggroll.DonationHandlerAPI.java
@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" }) private JSONObject GetData(request_type type, String url, String post) { Date start = new Date(); Date preconnect = start;/* www . j av a 2 s . c o m*/ Date postconnect = start; Date prejson = start; Date postjson = start; JSONObject j = new JSONObject("{}"); BufferedInputStream i = null; String rawcontent = ""; int available = 0; int responsecode = 0; long cl = 0; try { URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(5000); c.setReadTimeout(5000); c.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 QuorraBot/2015"); c.setRequestProperty("Content-Type", "application/json-rpc"); c.setRequestProperty("Content-length", "0"); if (!post.isEmpty()) { c.setDoOutput(true); } preconnect = new Date(); c.connect(); postconnect = new Date(); if (!post.isEmpty()) { try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) { IOUtils.write(post, o); } } String content; cl = c.getContentLengthLong(); responsecode = c.getResponseCode(); if (c.getResponseCode() == 200) { i = new BufferedInputStream(c.getInputStream()); } else { i = new BufferedInputStream(c.getErrorStream()); } /* * if (i != null) { available = i.available(); * * while (available == 0 && (new Date().getTime() - * postconnect.getTime()) < 450) { Thread.sleep(500); available = * i.available(); } * * if (available == 0) { i = new * BufferedInputStream(c.getErrorStream()); * * if (i != null) { available = i.available(); } } } * * if (available == 0) { content = "{}"; } else { content = * IOUtils.toString(i, c.getContentEncoding()); } */ content = IOUtils.toString(i, c.getContentEncoding()); rawcontent = content; prejson = new Date(); j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_available", available); j.put("_exception", ""); j.put("_exceptionMessage", ""); j.put("_content", content); postjson = new Date(); } catch (JSONException ex) { if (ex.getMessage().contains("A JSONObject text must begin with")) { j = new JSONObject("{}"); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")"); j.put("_exceptionMessage", ""); j.put("_content", rawcontent); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } if (i != null) { try { i.close(); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } } if (Quorrabot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Timers " + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime()) + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime()) + " " + start.toString() + " " + postjson.toString()); com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Exception " + j.getString("_exception") + " " + j.getString("_exceptionMessage")); com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData HTTP/Available " + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")"); com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData RawContent[0,100] " + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length()))); } return j; }
From source file:com.gmt2001.YouTubeAPIv3.java
@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" }) private JSONObject GetData(request_type type, String url, String post) { Date start = new Date(); Date preconnect = start;//w w w. j a v a 2 s . c o m Date postconnect = start; Date prejson = start; Date postjson = start; JSONObject j = new JSONObject("{}"); BufferedInputStream i = null; String rawcontent = ""; int available = 0; int responsecode = 0; long cl = 0; try { if (url.contains("?") && !url.contains("oembed?")) { url += "&utcnow=" + System.currentTimeMillis(); } else { if (!url.contains("oembed?")) { url += "?utcnow=" + System.currentTimeMillis(); } } URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(5000); c.setReadTimeout(5000); c.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"); c.setRequestProperty("Content-Type", "application/json-rpc"); c.setRequestProperty("Content-length", "0"); if (!post.isEmpty()) { c.setDoOutput(true); } preconnect = new Date(); c.connect(); postconnect = new Date(); if (!post.isEmpty()) { try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) { IOUtils.write(post, o); } } String content; cl = c.getContentLengthLong(); responsecode = c.getResponseCode(); if (c.getResponseCode() == 200) { i = new BufferedInputStream(c.getInputStream()); } else { i = new BufferedInputStream(c.getErrorStream()); } /* * if (i != null) { available = i.available(); * * while (available == 0 && (new Date().getTime() - * postconnect.getTime()) < 450) { Thread.sleep(500); available = * i.available(); } * * if (available == 0) { i = new * BufferedInputStream(c.getErrorStream()); * * if (i != null) { available = i.available(); } } } * * if (available == 0) { content = "{}"; } else { content = * IOUtils.toString(i, c.getContentEncoding()); } */ content = IOUtils.toString(i, c.getContentEncoding()); rawcontent = content; prejson = new Date(); j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_available", available); j.put("_exception", ""); j.put("_exceptionMessage", ""); j.put("_content", content); postjson = new Date(); } catch (JSONException ex) { if (ex.getMessage().contains("A JSONObject text must begin with")) { j = new JSONObject("{}"); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")"); j.put("_exceptionMessage", ""); j.put("_content", rawcontent); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } if (i != null) { try { i.close(); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } } if (PhantomBot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData Timers " + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime()) + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime()) + " " + start.toString() + " " + postjson.toString()); com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData Exception " + j.getString("_exception") + " " + j.getString("_exceptionMessage")); com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData HTTP/Available " + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")"); com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData RawContent[0,100] " + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length()))); } return j; }
From source file:me.rojo8399.placeholderapi.impl.Metrics.java
/** * Sends the data to the bStats server./* ww w. ja v a 2s . c o m*/ * * @param data * The data to send. * @throws Exception * If the request failed. */ private static void sendData(JsonObject data) throws Exception { Validate.notNull(data, "Data cannot be null"); HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip // our // request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We // send // our // data // in // JSON // format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); connection.getInputStream().close(); // We don't care about the response // - Just send our data :) }
From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java
/** * Queries the mtgox api with params//from w w w.j av a2 s .c om * * @param url * @return */ public String query(String path, HashMap<String, String> args) { final String publicKey = mtGoxConfig.getMtGoxPublicKey(); final String privateKey = mtGoxConfig.getMtGoxPrivateKey(); if (publicKey == null || privateKey == null || "".equals(publicKey) || "".equals(privateKey)) { throw new ApiKeysNotSetException( "Either public or private key of MtGox are not set. Please set them up in src/main/resources/META-INF/seam-beans.xml"); } // Create nonce final String nonce = String.valueOf(System.currentTimeMillis()) + "000"; HttpsURLConnection connection = null; String answer = null; try { // add nonce and build arg list args.put(ARG_KEY_NONCE, nonce); String post_data = buildQueryString(args); String hash_data = path + "\0" + post_data; // Should be correct // args signature with apache cryptografic tools String signature = signRequest(mtGoxConfig.getMtGoxPrivateKey(), hash_data); // build URL URL queryUrl = new URL(Constants.API_BASE_URL + path); // create and setup a HTTP connection connection = (HttpsURLConnection) queryUrl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty(REQ_PROP_USER_AGENT, com.dagobert_engine.core.util.Constants.APP_NAME); connection.setRequestProperty(REQ_PROP_REST_KEY, mtGoxConfig.getMtGoxPublicKey()); connection.setRequestProperty(REQ_PROP_REST_SIGN, signature.replaceAll("\n", "")); connection.setDoOutput(true); connection.setDoInput(true); // Read the response DataOutputStream os = new DataOutputStream(connection.getOutputStream()); os.writeBytes(post_data); os.close(); BufferedReader br = null; // Any error? int code = connection.getResponseCode(); if (code >= 400) { // get error stream br = new BufferedReader(new InputStreamReader((connection.getErrorStream()))); answer = toString(br); logger.severe("HTTP Error on queryin " + path + ": " + code + ", answer: " + answer); throw new MtGoxConnectionError(code, answer); } else { // get normal stream br = new BufferedReader(new InputStreamReader((connection.getInputStream()))); answer = toString(br); } } catch (UnknownHostException exc) { throw new MtGoxConnectionError("Could not connect to MtGox. Please check your internet connection. (" + exc.getClass().getName() + ")"); } catch (IllegalStateException ex) { throw new MtGoxConnectionError(ex); } catch (IOException ex) { throw new MtGoxConnectionError(ex); } finally { if (connection != null) connection.disconnect(); connection = null; } return answer; }
From source file:org.wso2.am.integration.tests.other.APIImportExportTestCase.java
/** * Upload a file to the given URL//from ww w. j a v a 2 s .c o m * * @param importUrl URL to be file upload * @param fileName Name of the file to be upload * @throws IOException throws if connection issues occurred */ private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException { //open import API url connection and deploy the exported API URL url = new URL(importUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(fileName); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Basic " + encodeCredentials(user, pass)); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream())); String temp; StringBuilder response = new StringBuilder(); while ((temp = read.readLine()) != null) { response.append(temp); } Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response); }
From source file:se.leap.bitmaskclient.ProviderAPI.java
/** * Executes an HTTP request expecting a JSON response. * * @param url// w w w .ja v a 2 s .c o m * @param request_method * @param parameters * @return response from authentication server */ private JSONObject sendToServer(String url, String request_method, Map<String, String> parameters) { JSONObject json_response; HttpsURLConnection urlConnection = null; try { InputStream is = null; urlConnection = (HttpsURLConnection) new URL(url).openConnection(); urlConnection.setRequestMethod(request_method); String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry(); urlConnection.setRequestProperty("Accept-Language", locale); urlConnection.setChunkedStreamingMode(0); urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory()); DataOutputStream writer = new DataOutputStream(urlConnection.getOutputStream()); writer.writeBytes(formatHttpParameters(parameters)); writer.close(); is = urlConnection.getInputStream(); String plain_response = new Scanner(is).useDelimiter("\\A").next(); json_response = new JSONObject(plain_response); } catch (ClientProtocolException e) { json_response = getErrorMessage(urlConnection); e.printStackTrace(); } catch (IOException e) { json_response = getErrorMessage(urlConnection); e.printStackTrace(); } catch (JSONException e) { json_response = getErrorMessage(urlConnection); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { json_response = getErrorMessage(urlConnection); e.printStackTrace(); } catch (KeyManagementException e) { json_response = getErrorMessage(urlConnection); e.printStackTrace(); } catch (KeyStoreException e) { json_response = getErrorMessage(urlConnection); e.printStackTrace(); } catch (CertificateException e) { json_response = getErrorMessage(urlConnection); e.printStackTrace(); } return json_response; }
From source file:com.carvoyant.modularinput.Program.java
private JSONObject getRefreshToken(EventWriter ew, String clientId, String clientSecret, String refreshToken) { JSONObject tokenJson = null;/*from w ww . ja v a2 s. c o m*/ HttpsURLConnection getTokenConnection = null; try { BufferedReader tokenResponseReader = null; URL url = new URL("https://api.carvoyant.com/oauth/token"); // URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/oauth/token"); getTokenConnection = (HttpsURLConnection) url.openConnection(); getTokenConnection.setReadTimeout(30000); getTokenConnection.setConnectTimeout(30000); getTokenConnection.setRequestMethod("POST"); getTokenConnection.setDoInput(true); getTokenConnection.setDoOutput(true); List<SimpleEntry> getTokenParams = new ArrayList<SimpleEntry>(); getTokenParams.add(new SimpleEntry("client_id", clientId)); getTokenParams.add(new SimpleEntry("client_secret", clientSecret)); getTokenParams.add(new SimpleEntry("grant_type", "refresh_token")); getTokenParams.add(new SimpleEntry("refresh_token", refreshToken)); String userpass = clientId + ":" + clientSecret; String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()); getTokenConnection.setRequestProperty("Authorization", basicAuth); OutputStream os = getTokenConnection.getOutputStream(); os.write(getQuery(getTokenParams).getBytes("UTF-8")); os.close(); if (getTokenConnection.getResponseCode() < 400) { tokenResponseReader = new BufferedReader( new InputStreamReader(getTokenConnection.getInputStream())); String inputLine; StringBuffer sb = new StringBuffer(); while ((inputLine = tokenResponseReader.readLine()) != null) { sb.append(inputLine); } tokenJson = new JSONObject(sb.toString()); ew.synchronizedLog(EventWriter.INFO, "Refreshed Carvoyant access token."); } else { tokenResponseReader = new BufferedReader( new InputStreamReader(getTokenConnection.getErrorStream())); StringBuffer sb = new StringBuffer(); String inputLine; while ((inputLine = tokenResponseReader.readLine()) != null) { sb.append(inputLine); } ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error. CLIENT_ID:" + clientId + ", REFRESH_TOKEN:" + refreshToken + ",ERROR_MSG: " + sb.toString()); } getTokenConnection.disconnect(); } catch (MalformedURLException mue) { ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + mue.getMessage()); } catch (IOException ioe) { ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + ioe.getMessage()); } finally { if (null != getTokenConnection) { getTokenConnection.disconnect(); } } return tokenJson; }