List of usage examples for javax.net.ssl HttpsURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:org.disrupted.rumble.database.statistics.StatisticManager.java
public void onEventAsync(LinkLayerStarted event) { if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier)) return;/*from w w w . j a v a 2 s . c o m*/ if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext()) && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) { if (!NetUtil.isURLReachable("http://disruptedsystems.org/")) return; try { // generate the JSON file byte[] json = generateStatJSON().toString().getBytes(); // configure SSL CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream( RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem")); Certificate ca = cf.generateCertificate(caInput); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://data.disruptedsystems.org/post"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); // then configure the header urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("charset", "utf-8"); urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length)); urlConnection.setUseCaches(false); // connect and send the JSON urlConnection.setConnectTimeout(10 * 1000); urlConnection.connect(); urlConnection.getOutputStream().write(json); if (urlConnection.getResponseCode() != 200) throw new IOException("request failed"); // erase the database RumblePreferences.updateLastSync(RumbleApplication.getContext()); cleanDatabase(); } catch (Exception ex) { Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString()); } } }
From source file:no.digipost.android.api.ApiAccess.java
public String postput(Context context, final int httpType, final String uri, final StringEntity json) throws DigipostClientException, DigipostApiException, DigipostAuthenticationException { HttpsURLConnection httpsClient; InputStream result = null;//from ww w.ja v a 2 s . co m try { URL url = new URL(uri); httpsClient = (HttpsURLConnection) url.openConnection(); if (httpType == POST) { httpsClient.setRequestMethod("POST"); } else if (httpType == PUT) { httpsClient.setRequestMethod("PUT"); } httpsClient.setRequestProperty(ApiConstants.CONTENT_TYPE, ApiConstants.APPLICATION_VND_DIGIPOST_V2_JSON); httpsClient.setRequestProperty(ApiConstants.ACCEPT, ApiConstants.APPLICATION_VND_DIGIPOST_V2_JSON); httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION, ApiConstants.BEARER + TokenStore.getAccess()); OutputStream outputStream; outputStream = new BufferedOutputStream(httpsClient.getOutputStream()); if (json != null) { json.writeTo(outputStream); } outputStream.flush(); int statusCode = httpsClient.getResponseCode(); try { NetworkUtilities.checkHttpStatusCode(context, statusCode); } catch (DigipostInvalidTokenException e) { OAuth.updateAccessTokenWithRefreshToken(context); return postput(context, httpType, uri, json); } if (statusCode == NetworkUtilities.HTTP_STATUS_NO_CONTENT) { return NetworkUtilities.SUCCESS_NO_CONTENT; } try { result = httpsClient.getInputStream(); } catch (IllegalStateException e) { Log.e(TAG, e.getMessage()); } } catch (IOException e) { throw new DigipostClientException(context.getString(R.string.error_your_network)); } return JSONUtilities.getJsonStringFromInputStream(result); }
From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java
public BulkImportResult executePostFileRequest(Class<?> resultClass, String filePath) throws MarketoException { String boundary = "Talend_tMarketoBulkExec_" + String.valueOf(System.currentTimeMillis()); try {// w ww . j a v a 2 s . c o m URL url = new URL(current_uri.toString()); HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); urlConn.setRequestProperty("accept", "text/json"); urlConn.setDoOutput(true); String requestBody = buildRequest(filePath); // build the request body PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream())); wr.append("--" + boundary + "\r\n"); wr.append("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\";\r\n"); wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n"); wr.append("Content-Transfer-Encoding: text/plain\r\n"); wr.append("MIME-Version: 1.0\r\n"); wr.append("\r\n"); wr.append(requestBody); wr.append("\r\n"); wr.append("--" + boundary); wr.flush(); wr.close(); int responseCode = urlConn.getResponseCode(); if (responseCode == 200) { InputStream inStream = urlConn.getInputStream(); InputStreamReader reader = new InputStreamReader(inStream); Gson gson = new Gson(); return (BulkImportResult) gson.fromJson(reader, resultClass); } else { LOG.error("POST request failed: {}", responseCode); throw new MarketoException(REST, responseCode, "Request failed! Please check your request setting!"); } } catch (IOException e) { LOG.error("POST request failed: {}", e.getMessage()); throw new MarketoException(REST, e.getMessage()); } }
From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java
public String[] callPostAndPut(String stringUrl, String body, String method) { try {/*from w w w.ja v a2s . c o 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:se.leap.bitmaskclient.ProviderAPI.java
private boolean logOut() { String delete_url = provider_api_url + "/logout"; HttpsURLConnection urlConnection = null; int responseCode = 0; int progress = 0; try {/*from w ww .ja va2s. c o m*/ urlConnection = (HttpsURLConnection) new URL(delete_url).openConnection(); urlConnection.setRequestMethod("DELETE"); urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory()); responseCode = urlConnection.getResponseCode(); broadcastProgress(progress++); LeapSRPSession.setToken(""); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IndexOutOfBoundsException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block try { if (urlConnection != null) { responseCode = urlConnection.getResponseCode(); if (responseCode == 401) { broadcastProgress(progress++); LeapSRPSession.setToken(""); return true; } } } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); return false; } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); // add request header if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); }/*from ww w . j a v a 2s . com*/ } int responseCode = con.getResponseCode(); logger.debug("Send GET http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { // result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response != null) { restResponse.setResponse(response.toString()); } restResponse.setErrorCode(responseCode); // restResponse.setResponse(result); Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:org.wso2.carbon.integration.common.tests.JaggeryServerTest.java
/** * Sending the request and getting the response * @param Uri - request url/*ww w. j a v a2 s . c o m*/ * @param append - append request parameters * @throws IOException */ private HttpsResponse getRequest(String Uri, String requestParameters, boolean append) throws IOException { if (Uri.startsWith("https://")) { String urlStr = Uri; if (requestParameters != null && requestParameters.length() > 0) { if (append) { urlStr += "?" + requestParameters; } else { urlStr += requestParameters; } } URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setReadTimeout(30000); conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } catch (IOException ignored) { } finally { if (rd != null) { rd.close(); } conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:com.gloriouseggroll.LastFMAPI.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 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] LastFMAPI.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] LastFMAPI.GetData Exception " + j.getString("_exception") + " " + j.getString("_exceptionMessage")); com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData HTTP/Available " + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")"); com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData RawContent[0,100] " + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length()))); } return j; }
From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java
/** * Send REST call//from w w w. j av a2 s .c o 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:tetujin.nikeapi.core.JNikeLowLevelAPI.java
/** * //from ww w . ja v a2s.c o m * @param strURL ?URL * @return jsonStr JSON?? */ protected String sendHttpRequest(final String strURL) { String jsonStr = ""; try { URL url = new URL(strURL); /*---------make and set HTTP header-------*/ //HttpsURLConnection baseConnection = (HttpsURLConnection)url.openConnection(); HttpsURLConnection con = setHttpHeader((HttpsURLConnection) url.openConnection()); /*---------show HTTP header information-------*/ System.out.println("\n ---------http header---------- "); Map headers = con.getHeaderFields(); for (Object key : headers.keySet()) { System.out.println(key + ": " + headers.get(key)); } con.connect(); /*---------get HTTP body information---------*/ String contentType = con.getHeaderField("Content-Type"); //String charSet = "Shift-JIS";// "ISO-8859-1"; String charSet = "UTF-8";// "ISO-8859-1"; for (String elm : contentType.replace(" ", "").split(";")) { if (elm.startsWith("charset=")) { charSet = elm.substring(8); break; } } /*---------show HTTP body information----------*/ BufferedReader br; try { br = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet)); } catch (Exception e_) { System.out.println(con.getResponseCode() + " " + con.getResponseMessage()); br = new BufferedReader(new InputStreamReader(con.getErrorStream(), charSet)); } System.out.println("\n ---------show HTTP body information----------"); String line = ""; while ((line = br.readLine()) != null) { jsonStr += line; } br.close(); con.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(jsonStr); return jsonStr; }