List of usage examples for javax.net.ssl HttpsURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.github.abilityapi.abilityapi.external.Metrics.java
/** * Sends the data to the bStats server./* www. ja v a2s .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.citrus.mobile.RESTclient.java
public JSONObject makeWithdrawRequest(String accessToken, double amount, String currency, String owner, String accountNumber, String ifscCode) { HttpsURLConnection conn; DataOutputStream wr = null;/*from www.j a va2 s.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:edu.purdue.cybercenter.dm.web.GlobusControllerTest.java
@Test @Ignore//from w w w . j a v a 2 s . co m public void shouldBeAbleToRunWorkflowWithGlobusTransfer() throws Exception { useTestWorkspace("brouder_sylvie"); login("george.washington", "1234"); /* * upload the test workflow */ MockMultipartFile mockMultipartFile = new MockMultipartFile(WORKFLOW_ZIP_FILE, new FileInputStream(WORKFLOW_FILES_DIR + WORKFLOW_ZIP_FILE)); MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload( "/workflows/import").accept(MediaType.ALL).session(httpSession); mockMultipartHttpServletRequestBuilder.file(mockMultipartFile); ResultActions resultActions = mockMvc.perform(mockMultipartHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); String content = extractTextarea(resultActions.andReturn().getResponse().getContentAsString()); Map<String, Object> workflow = Helper.deserialize(content, Map.class); assertNotNull("workflow is null", workflow); Integer workflowId = (Integer) workflow.get("id"); /* * create a project and an experiment to associate the job for the workflow with * while doing that, make sure we save all the IDs associated to post it with the job */ MockHttpServletRequestBuilder mockHttpServletRequestBuilder = post("/projects") .content("{\"description\":\"This is a project\",\"name\":\"Project 1\"}") .accept(MediaType.APPLICATION_JSON).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); content = resultActions.andReturn().getResponse().getContentAsString(); Map<String, Object> map = Helper.deserialize(content, Map.class); Integer projectId = (Integer) map.get("id"); mockHttpServletRequestBuilder = post("/experiments") .content("{\"projectId\":{\"$ref\":\"/projects/" + projectId + "\"},\"name\":\"Experiment 1\",\"description\":\"This is an experiment\"}") .accept(MediaType.APPLICATION_JSON).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); content = resultActions.andReturn().getResponse().getContentAsString(); map = Helper.deserialize(content, Map.class); Integer experimentId = (Integer) map.get("id"); /* * create a job associated with the project, experiment and workflow we just created */ mockHttpServletRequestBuilder = post("/jobs").param("projectId", projectId.toString()) .param("experimentId", experimentId.toString()).param("workflowId", workflowId.toString()) .param("name", "Just a job").accept(MediaType.TEXT_HTML).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); /* * forwarded to job/submit/jobId */ String forwardedUrl = resultActions.andReturn().getResponse().getForwardedUrl(); mockHttpServletRequestBuilder = post(forwardedUrl).accept(MediaType.TEXT_HTML_VALUE).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); /* * redirected to jobs/task/jobId */ String redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); mockHttpServletRequestBuilder = get(redirectedUrl).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); /* * we're at UT1 in the workflow */ String jobId = redirectedUrl.substring(redirectedUrl.lastIndexOf('/') + 1); TaskEntity task = (TaskEntity) resultActions.andReturn().getModelAndView().getModel().get("task"); String taskId = task.getId(); String templateId = "305b0f27-e829-424e-84eb-7a8a9ed93e28"; String templateVersion = "db719406-f665-45cb-a8fb-985b6082b654"; // For buttton 1 UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("multiple", false); System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize"); uriBuilder.queryParam("response_type", "code"); //uriBuilder.queryParam("redirect_uri", "code"); uriBuilder.queryParam("client_id", username); URL url = new URL(uriBuilder.build(true).toUriString()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); String userpass = username + ":" + password; String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); String res = IOUtils.toString(connection.getInputStream()); Map<String, Object> responseMap = Helper.deserialize(res, Map.class); String code = (String) responseMap.get("code"); uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback"); uriBuilder.queryParam("jobId", Integer.parseInt(jobId)); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("multiple", false); String uri = uriBuilder.build(true).toUriString() + "&code=" + code; mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); // For Button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("multiple", true); System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize"); uriBuilder.queryParam("response_type", "code"); uriBuilder.queryParam("client_id", username); url = new URL(uriBuilder.build(true).toUriString()); connection = (HttpsURLConnection) url.openConnection(); userpass = username + ":" + password; basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); res = IOUtils.toString(connection.getInputStream()); responseMap = Helper.deserialize(res, Map.class); code = (String) responseMap.get("code"); // For button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback"); uriBuilder.queryParam("jobId", Integer.parseInt(jobId)); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("multiple", true); uri = uriBuilder.build(true).toUriString() + "&code=" + code; mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); // Getting accessToken only from one button String accessToken = ""; String[] urlParts = redirectedUrl.split("&"); for (String urlPart : urlParts) { if (urlPart.contains("accessToken")) { String[] accessTokenPair = urlPart.split("="); accessToken = accessTokenPair[1]; break; } } //Button 1 uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); //Button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1); uriBuilder.queryParam(URLEncoder.encode("file[1]", "UTF-8"), FILE_TO_UPLOAD_2); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); //For getting Storage Files (an abstract button called browsefile3) uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile3"); uriBuilder.queryParam("multiple", true); uriBuilder.queryParam("storageFile", "StorageFile:1");// This file has to be present in the storage file record and in memory System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); //FileSelect uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam("fileId", 1); uriBuilder.queryParam(URLEncoder.encode("folder[0]", "UTF-8"), "remote_endpoint/"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile3"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri, "UTF-8"); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); String multipartBoundary = "------WebKitFormBoundary3xeGH8uP6GWtBfd1"; MultiPartFileContentBuilder multiPartFileContentBuilder = new MultiPartFileContentBuilder( multipartBoundary); multiPartFileContentBuilder.addField("autoGenerated", "true"); multiPartFileContentBuilder.addField("jobId", jobId); multiPartFileContentBuilder.addField("taskId", taskId); multiPartFileContentBuilder.addField("jsonToServer", "{}"); multiPartFileContentBuilder.addField("isIframe", "true"); multiPartFileContentBuilder.addField("experimentId", ""); multiPartFileContentBuilder.addField("projectId", ""); multiPartFileContentBuilder .addField(templateId + ".name({%22_template_version:%22" + templateVersion + "%22})", ""); multiPartFileContentBuilder .addField(templateId + ".browsefile1({%22_template_version:%22" + templateVersion + "%22})", ""); multiPartFileContentBuilder .addField(templateId + ".browsefile2({%22_template_version:%22" + templateVersion + "%22})", ""); String taskContent = multiPartFileContentBuilder.build(); // /rest/objectus post call mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/rest/objectus/") .param("jobId", jobId).param("taskId", taskId).param(templateId + ".name", "") .param(templateId + ".browsefile1", "").param(templateId + ".browsefile2", "") .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession); mockHttpServletRequestBuilder.content(taskContent); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); multipartBoundary = "------WebKitFormBoundarybiQtLhfKnPwaMgsR"; multiPartFileContentBuilder = new MultiPartFileContentBuilder(multipartBoundary); multiPartFileContentBuilder.addField("jobId", jobId); multiPartFileContentBuilder.addField("taskId", taskId); multiPartFileContentBuilder.addField("jsonToServer", "{}"); taskContent = multiPartFileContentBuilder.build(); // /jobs/task post call mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/jobs/task") .param("jobId", jobId).param("taskId", taskId).param("ignoreFormData", "true") .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession); mockHttpServletRequestBuilder.content(taskContent); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); deleteDatasetEntries(templateId); }
From source file:com.dao.ShopThread.java
private HttpsURLConnection getHttpSConn(String httpsurl) throws Exception { // SSLContext?? TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); // Acts like a browser URL obj = new URL(httpsurl); HttpsURLConnection conn; conn = (HttpsURLConnection) obj.openConnection(); conn.setSSLSocketFactory(ssf);//w w w.j ava2 s . c o m conn.setRequestMethod("GET"); if (null != this.cookies) { conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies)); } conn.setRequestProperty("Host", "security.5173.com"); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("Pragma", "no-cache"); conn.setRequestProperty("Cache-Control", "no-cache"); conn.setDoOutput(true); conn.setDoInput(true); return conn; }
From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java
private void uploadAttachment(String method, String url, InputStream data, long dataSize, byte[] key, ProgressListener listener) throws IOException { URL uploadUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection(); connection.setDoOutput(true);/*from w ww .java 2 s . c om*/ if (dataSize > 0) { connection .setFixedLengthStreamingMode((int) AttachmentCipherOutputStream.getCiphertextLength(dataSize)); } else { connection.setChunkedStreamingMode(0); } connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setRequestProperty("Connection", "close"); connection.connect(); try { OutputStream stream = connection.getOutputStream(); AttachmentCipherOutputStream out = new AttachmentCipherOutputStream(key, stream); byte[] buffer = new byte[4096]; int read, written = 0; while ((read = data.read(buffer)) != -1) { out.write(buffer, 0, read); written += read; if (listener != null) { listener.onAttachmentProgress(dataSize, written); } } data.close(); out.flush(); out.close(); if (connection.getResponseCode() != 200) { throw new IOException( "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } }
From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java
/** * Send REST call/*from w w w. j a va2 s.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.dagobert_engine.core.service.MtGoxApiAdapter.java
/** * Queries the mtgox api with params//from w w w . jav a 2 s .c o m * * @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.appspot.apprtc.util.AsyncHttpURLConnection.java
private void sendHttpMessage() { if (mIsBitmap) { Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url); if (bitmap != null) { events.onHttpComplete(bitmap); return; }/*from www. j a va 2s . c o m*/ } X509TrustManager trustManager = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE : This is where we can calculate the certificate's fingerprint, // show it to the user and throw an exception in case he doesn't like it } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }; //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier()); // Create a trust manager that does not validate certificate chains X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager }; // Install the all-trusting trust manager SSLSocketFactory noSSLv3Factory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom()); } else { noSSLv3Factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory); } catch (GeneralSecurityException e) { } HttpsURLConnection connection = null; try { URL urlObj = new URL(url); connection = (HttpsURLConnection) urlObj.openConnection(); connection.setSSLSocketFactory(noSSLv3Factory); HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost())); connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost())); byte[] postData = new byte[0]; if (message != null) { postData = message.getBytes("UTF-8"); } if (msCookieManager.getCookieStore().getCookies().size() > 0) { // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';' connection.setRequestProperty("Cookie", TextUtils.join(";", msCookieManager.getCookieStore().getCookies())); } /*if (method.equals("PATCH")) { connection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); connection.setRequestMethod("POST"); } else {*/ connection.setRequestMethod(method); //} if (authorization.length() != 0) { connection.setRequestProperty("Authorization", authorization); } connection.setUseCaches(false); connection.setDoInput(true); connection.setConnectTimeout(HTTP_TIMEOUT_MS); connection.setReadTimeout(HTTP_TIMEOUT_MS); // TODO(glaznev) - query request origin from pref_room_server_url_key preferences. //connection.addRequestProperty("origin", HTTP_ORIGIN); boolean doOutput = false; if (method.equals("POST") || method.equals("PATCH")) { doOutput = true; connection.setDoOutput(true); connection.setFixedLengthStreamingMode(postData.length); } if (contentType == null) { connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); } else { connection.setRequestProperty("Content-Type", contentType); } // Send POST request. if (doOutput && postData.length > 0) { OutputStream outStream = connection.getOutputStream(); outStream.write(postData); outStream.close(); } // Get response. int responseCode = 200; try { connection.getResponseCode(); } catch (IOException e) { } getCookies(connection); InputStream responseStream; if (responseCode > 400) { responseStream = connection.getErrorStream(); } else { responseStream = connection.getInputStream(); } String responseType = connection.getContentType(); if (responseType.startsWith("image/")) { Bitmap bitmap = BitmapFactory.decodeStream(responseStream); if (mIsBitmap && bitmap != null) { ThumbnailsCacheManager.addBitmapToCache(url, bitmap); } events.onHttpComplete(bitmap); } else { String response = drainStream(responseStream); events.onHttpComplete(response); } responseStream.close(); connection.disconnect(); } catch (SocketTimeoutException e) { events.onHttpError("HTTP " + method + " to " + url + " timeout"); } catch (IOException e) { if (connection != null) { connection.disconnect(); } events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage()); } catch (ClassCastException e) { e.printStackTrace(); } }
From source file:org.exoplatform.services.videocall.AuthService.java
public String authenticate(VideoCallModel videoCallModel, String profile_id) { VideoCallService videoCallService = new VideoCallService(); if (videoCallModel == null) { caFile = videoCallService.getPemCertInputStream(); p12File = videoCallService.getP12CertInputStream(); videoCallModel = videoCallService.getVideoCallProfile(); } else {//from ww w .jav a 2 s.c o m caFile = videoCallModel.getPemCert(); p12File = videoCallModel.getP12Cert(); } if (videoCallModel != null) { domain_id = videoCallModel.getDomainId(); clientId = videoCallModel.getAuthId(); clientSecret = videoCallModel.getAuthSecret(); passphrase = videoCallModel.getCustomerCertificatePassphrase(); } String responseContent = null; if (StringUtils.isEmpty(passphrase)) return null; if (caFile == null || p12File == null) return null; try { String userId = ConversationState.getCurrent().getIdentity().getUserId(); SSLContext ctx = SSLContext.getInstance("SSL"); URL url = null; try { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(authUrl).append("?client_id=" + clientId).append("&client_secret=" + clientSecret) .append("&uid=weemo" + userId) .append("&identifier_client=" + URLEncoder.encode(domain_id, "UTF-8")) .append("&id_profile=" + URLEncoder.encode(profile_id, "UTF-8")); url = new URL(urlBuilder.toString()); } catch (MalformedURLException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not create valid URL with base", e); } } HttpsURLConnection connection = null; try { connection = (HttpsURLConnection) url.openConnection(); } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not connect", e); } } TrustManager[] trustManagers = getTrustManagers(caFile, passphrase); KeyManager[] keyManagers = getKeyManagers("PKCS12", p12File, passphrase); ctx.init(keyManagers, trustManagers, new SecureRandom()); try { connection.setSSLSocketFactory(ctx.getSocketFactory()); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Could not configure request for POST", e); } } try { connection.connect(); } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not connect to weemo", e); } } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sbuilder = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sbuilder.append(line + "\n"); } br.close(); responseContent = sbuilder.toString(); // Set new token key String tokenKey = ""; if (!StringUtils.isEmpty(responseContent)) { JSONObject json = new JSONObject(responseContent); tokenKey = json.get("token").toString(); } else { tokenKey = ""; } videoCallService.setTokenKey(tokenKey); } catch (Exception ex) { LOG.error("Have problem during authenticating process.", ex); videoCallService.setTokenKey(""); } return responseContent; }