List of usage examples for javax.net.ssl HttpsURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:tangocard.sdk.service.ServiceProxy.java
/** * Post request.// www . j av a 2s . co 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: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 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:org.openhab.binding.unifi.internal.UnifiBinding.java
private boolean login() { String url = null;/* w w w .j a v a 2s . co 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:com.qpark.eip.core.spring.security.https.EipHttpsClientHttpRequestFactory.java
/** * @see org.springframework.http.client.SimpleClientHttpRequestFactory#prepareConnection(java.net.HttpURLConnection, * java.lang.String)/*from w ww. ja v a2 s . c o m*/ */ @Override protected void prepareConnection(final HttpURLConnection connection, final String httpMethod) { try { /* Setup HttpsURLConnection. */ if (HttpsURLConnection.class.isInstance(connection)) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setHostnameVerifier(this.x509TrustManager); TrustManager[] trustManagers = new TrustManager[] { this.x509TrustManager }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagers, new java.security.SecureRandom()); ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } super.prepareConnection(connection, httpMethod); /* Setup the basic Authentication. */ if (HttpURLConnection.class.isInstance(connection) && this.userName != null) { HttpURLConnection httpsConnection = connection; httpsConnection.setRequestProperty("Authorization", new StringBuffer(128).append("Basic ").append(this.base64UserNamePassword).toString()); } } catch (Exception e) { e.printStackTrace(); } }
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 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:org.openhab.binding.jablotron.internal.JablotronBinding.java
private JablotronResponse sendUserCode(String code) { String url = null;//from w w w . j a v a2s . c om try { url = JABLOTRON_URL + "app/oasis/ajax/ovladani.php"; String urlParameters = "section=STATE&status=" + ((code.isEmpty()) ? "1" : "") + "&code=" + code; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); JablotronResponse response; synchronized (session) { connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Referer", JABLOTRON_URL + SERVICE_URL + service); connection.setRequestProperty("Cookie", session); connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); connection.setRequestProperty("X-Requested-With", "XMLHttpRequest"); setConnectionDefaults(connection); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } response = new JablotronResponse(connection); } logger.debug("sendUserCode response: {}", response.getResponse()); return response; } catch (Exception ex) { logger.error("sendUserCode exception: {}", ex.toString()); } return null; }
From source file:org.openhab.binding.unifi.internal.UnifiBinding.java
private String sendToController(String url, String urlParameters, String method) { try {/*from w ww .j a va2s.c o m*/ synchronized (cookies) { byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestMethod(method); //for(String cookie : cookies) { connection.setRequestProperty("Cookie", cookies.get(0) + "; " + cookies.get(1)); //} if (urlParameters.length() > 0) { connection.setDoOutput(true); connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); connection.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } } InputStream response = connection.getInputStream(); String line = readResponse(response); if (!checkResponse(line)) { logger.error("Unifi response: " + line); } return line; } } catch (MalformedURLException e) { logger.error("The URL '" + url + "' is malformed: " + e.toString()); } catch (Exception e) { logger.error("Cannot send data " + urlParameters + " to url " + url + ". Exception: " + e.toString()); } return ""; }
From source file:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java
private ArrayList<LatLng> fetchPlacesFromAPI(LatLng center, int radius) { ArrayList<LatLng> places = new ArrayList<>(); radius = Math.min(radius, 50000); // Max accepted radius is 50km. try {/* w w w. ja v a 2s . c o m*/ InputStream is = null; URL url = new URL(getString(R.string.places_api_url) + "?location=" + center.latitude + "," + center.longitude + "&radius=" + radius); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); // Pass package name and signature as part of request String packageName = getPackageName(); String signature = getAppSignature(); conn.setRequestProperty("X-App-Package", packageName); conn.setRequestProperty("X-App-Signature", signature); conn.connect(); int response = conn.getResponseCode(); if (response != 200) { Log.e(TAG, "Places API HTTP error: " + response + " / " + url); } else { BufferedReader reader; StringBuilder builder = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (String line; (line = reader.readLine()) != null;) { builder.append(line); } JSONArray resultsJson = (new JSONObject(builder.toString())).getJSONArray("results"); for (int i = 0; i < resultsJson.length(); i++) { JSONObject latLngJson = ((JSONObject) resultsJson.get(i)).getJSONObject("geometry") .getJSONObject("location"); places.add(new LatLng(latLngJson.getDouble("lat"), latLngJson.getDouble("lng"))); } } } catch (Exception e) { Log.e(TAG, "Exception parsing places API: " + e.toString()); } return places; }
From source file:org.openhab.binding.jablotron.internal.JablotronBinding.java
private void login() { String url = null;/* w w w . j av a 2 s . co m*/ try { //login stavA = 0; stavB = 0; stavABC = 0; stavPGX = 0; stavPGY = 0; url = JABLOTRON_URL + "ajax/login.php"; String urlParameters = "login=" + email + "&heslo=" + password + "&aStatus=200&loginType=Login"; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); synchronized (session) { connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Referer", JABLOTRON_URL); connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); connection.setRequestProperty("X-Requested-With", "XMLHttpRequest"); setConnectionDefaults(connection); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } JablotronResponse response = new JablotronResponse(connection); if (response.getException() != null) { logger.error("JablotronResponse login exception: {}", response.getException()); return; } if (!response.isOKStatus()) return; //get cookie session = response.getCookie(); //cloud request url = JABLOTRON_URL + "ajax/widget-new.php?" + getBrowserTimestamp(); ; cookieUrl = new URL(url); connection = (HttpsURLConnection) cookieUrl.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Referer", JABLOTRON_URL + "cloud"); connection.setRequestProperty("Cookie", session); connection.setRequestProperty("X-Requested-With", "XMLHttpRequest"); setConnectionDefaults(connection); //line = readResponse(connection); response = new JablotronResponse(connection); if (response.getException() != null) { logger.error("JablotronResponse widget exception: {}", response.getException().toString()); return; } if (response.getResponseCode() != 200 || !response.isOKStatus()) { return; } if (response.getWidgetsCount() == 0) { logger.error("Cannot found any jablotron device"); return; } service = response.getServiceId(0); //service request url = response.getServiceUrl(0); if (!services.contains(service)) { services.add(service); logger.info("Found Jablotron service: {} id: {}", response.getServiceName(0), service); } cookieUrl = new URL(url); connection = (HttpsURLConnection) cookieUrl.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Referer", JABLOTRON_URL); connection.setRequestProperty("Cookie", session); connection.setRequestProperty("Upgrade-Insecure-Requests", "1"); setConnectionDefaults(connection); if (connection.getResponseCode() == 200) { logger.debug("Successfully logged to Jablotron cloud!"); } else { logger.error("Cannot log in to Jablotron cloud!"); } } } catch (MalformedURLException e) { logger.error("The URL '{}' is malformed: {}", url, e.toString()); } catch (Exception e) { logger.error("Cannot get Jablotron login cookie: {}", e.toString()); } }
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//from www .ja v a2s. co 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(); } }