List of usage examples for javax.net.ssl HttpsURLConnection connect
public abstract void connect() throws IOException;
From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java
private void revokeToken(final String token) { new AsyncTask<Void, Void, Void>() { @Override/* w w w. j av a2s . co m*/ protected Void doInBackground(Void... dummy) { try { HttpsURLConnection nection = (HttpsURLConnection) new URL("https://api.github.com/applications/" + BuildConfig.GITHUB_CLIENT_ID + "/tokens/" + token).openConnection(); nection.setRequestMethod("DELETE"); String encoded = Base64.encodeToString( (BuildConfig.GITHUB_CLIENT_ID + ":" + BuildConfig.GITHUB_CLIENT_SECRET).getBytes(), Base64.DEFAULT); nection.setRequestProperty("Authorization", "Basic " + encoded); nection.connect(); } catch (IOException e) { // nvm } return null; } }.execute(); }
From source file:com.mb.ext.web.controller.UserController.java
@RequestMapping(value = "/getAirQuality", method = RequestMethod.GET) @ResponseStatus(HttpStatus.CREATED)/* w w w . j av a 2s .c o m*/ @ResponseBody public ResultDTO getAirQuality() { // AirQualityDTO airQualityDTO = new AirQualityDTO(); ResultDTO resultDTO = new ResultDTO(); String result = null; try { String httpUrl = Constants.WEATHER_URL; BufferedReader reader = null; InputStream is = null; StringBuffer sbf = new StringBuffer(); try { URL url = new URL(httpUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); 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"); } result = sbf.toString(); } catch (Exception e) { e.printStackTrace(); } finally { reader.close(); is.close(); } resultDTO.setCode("0"); resultDTO.setMessage("Get air quality successfully"); } catch (Exception e) { resultDTO.setCode("1"); resultDTO.setMessage(e.getMessage()); } resultDTO.setBody(result); return resultDTO; }
From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java
public String[] callPostAndPut(String stringUrl, String body, String method) { try {//w w w. j a va 2s. co 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: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;/*from w ww . j a va 2s . c om*/ 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;//from w ww . ja v a2 s . co 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:io.github.protino.codewatch.remote.FetchLeaderBoardData.java
private List<String> fetchLeaderBoardJson() { HttpsURLConnection urlConnection = null; BufferedReader reader = null; List<String> jsonDataList = new ArrayList<>(); try {/*w ww . ja v a2 s . c om*/ final String LEADER_PATH = "leaders"; final String API_SUFFIX = "api/v1"; final String API_KEY = "api_key"; final String PAGE = "page"; Uri.Builder builder; String jsonStr; int totalPages = -1; int page = 1; do { builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon(); builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH) .appendQueryParameter(API_KEY, BuildConfig.API_KEY) .appendQueryParameter(PAGE, String.valueOf(page)).build(); URL url = new URL(builder.toString()); // Create the request to Wakatime.com, and open the connection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a string InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } if (buffer.length() == 0) { return null; } jsonStr = buffer.toString(); jsonDataList.add(jsonStr); //parse totalpages if (totalPages == -1) { totalPages = new JSONObject(jsonStr).getInt("total_pages"); } page++; } while (totalPages != page); } catch (IOException e) { Timber.e(e, "IO Error"); } catch (JSONException e) { Timber.e(e, "JSON error"); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); Timber.e(e, "Error closing stream"); } } } return jsonDataList; }
From source file:io.github.protino.codewatch.remote.FetchLeaderBoardData.java
public int fetchUserRank() { AccessToken accessToken = CacheUtils.getAccessToken(context); if (accessToken == null) { return -1; }//from w w w .j a v a2 s . c om HttpsURLConnection urlConnection = null; BufferedReader reader = null; String jsonStr; try { final String LEADER_PATH = "leaders"; final String API_SUFFIX = "api/v1"; final String CLIENT_SECRET = "secret"; final String APP_SECRET = "app_secret"; final String ACCESS_TOKEN = "token"; Uri.Builder builder; builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon(); builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH) .appendQueryParameter(APP_SECRET, BuildConfig.CLIENT_ID) .appendQueryParameter(CLIENT_SECRET, BuildConfig.CLIENT_SECRET) .appendQueryParameter(ACCESS_TOKEN, accessToken.getAccessToken()).build(); URL url = new URL(builder.toString()); // Create the request to Wakatime.com, and open the connection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a string InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { return -1; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } if (buffer.length() == 0) { return -1; } jsonStr = buffer.toString(); JSONObject currentUser = new JSONObject(jsonStr).getJSONObject("current_user"); if (currentUser == null) { return -1; } else { //if is a new user, it'll result throw JSONException, because rank=null return currentUser.getInt("rank"); } } catch (IOException e) { Timber.e(e, "IO Error"); return -1; } catch (JSONException e) { Timber.e(e, "JSON error"); return -1; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); Timber.e(e, "Error closing stream"); } } } }
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 w w w. j a v 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; }
From source file:com.adobe.ibm.watson.traits.impl.WatsonServiceClient.java
/** * Fetches the IBM Watson Personal Insights report using the user's Twitter Timeline. * @param language/*w w w . j a va2s . c o m*/ * @param tweets * @param resource * @return * @throws Exception */ public String getWatsonScore(String language, String tweets, Resource resource) throws Exception { HttpsURLConnection connection = null; // Check if the username and password have been injected to the service. // If not, extract them from the cloud service configuration attached to the page. if (this.username == null || this.password == null) { getWatsonCloudSettings(resource); } // Build the request to IBM Watson. log.info("The Base Url is: " + this.baseUrl); String encodedCreds = getBasicAuthenticationEncoding(); URL url = new URL(this.baseUrl + "/v2/profile"); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Language", language); connection.setRequestProperty("Accept-Language", "en-us"); connection.setRequestProperty("Content-Type", ContentType.TEXT_PLAIN.toString()); connection.setRequestProperty("Authorization", "Basic " + encodedCreds); connection.setUseCaches(false); connection.getOutputStream().write(tweets.getBytes()); connection.getOutputStream().flush(); connection.connect(); log.info("Parsing response from Watson"); StringBuilder str = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = ""; while ((line = br.readLine()) != null) { str.append(line + System.getProperty("line.separator")); } if (connection.getResponseCode() != 200) { // The call failed, throw an exception. log.error(connection.getResponseCode() + " : " + connection.getResponseMessage()); connection.disconnect(); throw new Exception("IBM Watson Server responded with an error: " + connection.getResponseMessage()); } else { connection.disconnect(); return str.toString(); } }
From source file:iracing.webapi.IracingWebApi.java
/** * // w w w . j a v a 2 s .c o m * @return a login response code * @throws IOException * @throws LoginException * @see #LOGIN_RESPONSE_SUCCESS * @see #LOGIN_RESPONSE_CONNECTION_ERROR * @see #LOGIN_RESPONSE_DOWN_FOR_MAINTAINENCE * @see #LOGIN_RESPONSE_FAILED_CREDENTIALS */ public LoginResponse login() throws IOException, LoginException { try { installCerts(); } catch (Exception e1) { e1.printStackTrace(); throw new LoginException("error whilst attempting to install SSL certificates"); } System.setProperty("javax.net.ssl.trustStore", "jssecacerts"); System.setProperty("javax.net.ssl.trustStorePassword", CERT_STORE_PASSWORD); if (loginRequiredHandler == null) return LoginResponse.ConfigError; IracingLoginCredentials creds = new IracingLoginCredentials(); if (!loginRequiredHandler.onLoginCredentialsRequired(creds)) return LoginResponse.CredentialsError; String encodedUsername = URLEncoder.encode(creds.getEmailAddress(), "UTF-8"); String encodedPW = URLEncoder.encode(creds.getPassword(), "UTF-8"); String urltext = LOGIN_URL + "?username=" + encodedUsername + "&password=" + encodedPW; // + "&utcoffset=-60&todaysdate="; URL url = new URL(urltext); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.addRequestProperty("Content-Length", "0"); conn.setInstanceFollowRedirects(false); HttpsURLConnection.setFollowRedirects(false); try { conn.connect(); } catch (Exception e) { e.printStackTrace(); throw new LoginException(e.getMessage()); } if (isMaintenancePage(conn)) return LoginResponse.DownForMaintenance; String headerName; for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equalsIgnoreCase(SET_COOKIE)) { addToCookieMap(conn.getHeaderField(i)); } else { if (!headerName.equals("Location")) { continue; } String location2 = conn.getHeaderField(i); if (location2.indexOf("failedlogin") != -1) { throw new LoginException("You have been directed to the failed login page"); } } } createCookieFromMap(); conn.disconnect(); return LoginResponse.Success; }