List of usage examples for javax.net.ssl HttpsURLConnection getResponseCode
public int getResponseCode() throws IOException
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 . j a v a 2 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: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 w w . j ava 2 s.com*/ 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:org.wso2.am.integration.tests.other.APIImportExportTestCase.java
/** * Upload a file to the given URL//from w ww . ja v a 2 s. com * * @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:com.dagobert_engine.core.service.MtGoxApiAdapter.java
/** * Queries the mtgox api with params/* w ww . 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:com.carvoyant.modularinput.Program.java
private JSONObject getRefreshToken(EventWriter ew, String clientId, String clientSecret, String refreshToken) { JSONObject tokenJson = null;/*from w w w . j a v a 2 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; }
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 w w w .j a v a 2s . 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(); } }
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 w w.java 2 s.c o m*/ 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:com.gmt2001.TwitchAPIv3.java
@SuppressWarnings("UseSpecificCatch") private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) { JSONObject j = new JSONObject("{}"); InputStream i = null;// www . j a v a2 s . c o m String rawcontent = ""; try { if (url.contains("?")) { url += "&utcnow=" + System.currentTimeMillis(); } else { url += "?utcnow=" + System.currentTimeMillis(); } URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.addRequestProperty("Accept", header_accept); if (isJson) { c.addRequestProperty("Content-Type", "application/json"); } else { c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } if (!clientid.isEmpty()) { c.addRequestProperty("Client-ID", clientid); } if (!oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(timeout); 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"); if (!post.isEmpty()) { c.setDoOutput(true); } c.connect(); if (!post.isEmpty()) { try (OutputStream o = c.getOutputStream()) { IOUtils.write(post, o); } } String content; if (c.getResponseCode() == 200) { i = c.getInputStream(); } else { i = c.getErrorStream(); } if (c.getResponseCode() == 204 || i == null) { content = "{}"; } else { content = IOUtils.toString(i, c.getContentEncoding()); } rawcontent = content; 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("_exception", ""); j.put("_exceptionMessage", ""); j.put("_content", content); } 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("_exception", ""); 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("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); 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("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); 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("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); 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("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); 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("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); com.gmt2001.Console.err.logStackTrace(ex); } } return j; }
From source file:io.teak.sdk.Session.java
private void startHeartbeat() { final Session _this = this; this.heartbeatService = Executors.newSingleThreadScheduledExecutor(); this.heartbeatService.scheduleAtFixedRate(new Runnable() { public void run() { if (Teak.isDebug) { Log.v(LOG_TAG, "Sending heartbeat for user: " + userId); }//from www . j a va 2 s. c om HttpsURLConnection connection = null; try { String queryString = "game_id=" + URLEncoder.encode(_this.appConfiguration.appId, "UTF-8") + "&api_key=" + URLEncoder.encode(_this.userId, "UTF-8") + "&sdk_version=" + URLEncoder.encode(Teak.SDKVersion, "UTF-8") + "&sdk_platform=" + URLEncoder.encode(_this.deviceConfiguration.platformString, "UTF-8") + "&app_version=" + URLEncoder.encode(String.valueOf(_this.appConfiguration.appVersion), "UTF-8") + (_this.countryCode == null ? "" : "&country_code=" + URLEncoder.encode(String.valueOf(_this.countryCode), "UTF-8")) + "&buster=" + URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8"); URL url = new URL("https://iroko.gocarrot.com/ping?" + queryString); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setUseCaches(false); int responseCode = connection.getResponseCode(); if (Teak.isDebug) { Log.v(LOG_TAG, "Heartbeat response code: " + responseCode); } } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); } finally { if (connection != null) { connection.disconnect(); } } } }, 0, 1, TimeUnit.MINUTES); // TODO: If RemoteConfiguration specifies a different rate, use that }