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 makeSendMoneyRequest(String accessToken, CitrusUser toUser, Amount amount, String message) { HttpsURLConnection conn; DataOutputStream wr = null;/*from w w w . j av a 2 s. co m*/ JSONObject txnDetails = null; BufferedReader in = null; try { String url = null; StringBuffer postDataBuff = new StringBuffer("amount="); postDataBuff.append(amount.getValue()); postDataBuff.append("¤cy="); postDataBuff.append(amount.getCurrency()); postDataBuff.append("&message="); postDataBuff.append(message); if (!TextUtils.isEmpty(toUser.getEmailId())) { url = urls.getString(base_url) + urls.getString("transfer"); postDataBuff.append("&to="); postDataBuff.append(toUser.getEmailId()); } else if (!TextUtils.isEmpty(toUser.getMobileNo())) { url = urls.getString(base_url) + urls.getString("suspensetransfer"); postDataBuff.append("&to="); postDataBuff.append(toUser.getMobileNo()); } conn = (HttpsURLConnection) new URL(url).openConnection(); //add reuqest header conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + accessToken); conn.setDoOutput(true); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(postDataBuff.toString()); wr.flush(); int responseCode = conn.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + postDataBuff.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.pearson.pdn.learningstudio.core.AbstractService.java
/** * Performs HTTP operations using the selected authentication method * //w w w . ja v a2 s . com * @param extraHeaders Extra headers to include in the request * @param method The HTTP Method to user * @param relativeUrl The URL after .com (/me) * @param body The body of the message * @return Output in the preferred data format * @throws IOException */ protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl, String body) throws IOException { if (body == null) { body = ""; } // append .xml extension when XML data format enabled. if (dataFormat == DataFormat.XML) { logger.debug("Using XML extension on route"); String queryString = ""; int queryStringIndex = relativeUrl.indexOf('?'); if (queryStringIndex != -1) { queryString = relativeUrl.substring(queryStringIndex); relativeUrl = relativeUrl.substring(0, queryStringIndex); } String compareUrl = relativeUrl.toLowerCase(); if (!compareUrl.endsWith(".xml")) { relativeUrl += ".xml"; } if (queryStringIndex != -1) { relativeUrl += queryString; } } final String fullUrl = API_DOMAIN + relativeUrl; if (logger.isDebugEnabled()) { logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body); } URL url = new URL(fullUrl); Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body); if (oauthHeaders == null) { throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods"); } if (extraHeaders != null) { for (String key : extraHeaders.keySet()) { if (!oauthHeaders.containsKey(key)) { oauthHeaders.put(key, extraHeaders.get(key)); } else { throw new RuntimeException("Extra headers can not include OAuth headers"); } } } HttpsURLConnection request = (HttpsURLConnection) url.openConnection(); try { request.setRequestMethod(method.toString()); Set<String> oauthHeaderKeys = oauthHeaders.keySet(); for (String oauthHeaderKey : oauthHeaderKeys) { request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey)); } request.addRequestProperty("User-Agent", getServiceIdentifier()); if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) { if (dataFormat == DataFormat.XML) { request.setRequestProperty("Content-Type", "application/xml"); } else { request.setRequestProperty("Content-Type", "application/json"); } request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length)); request.setDoOutput(true); DataOutputStream out = new DataOutputStream(request.getOutputStream()); try { out.writeBytes(body); out.flush(); } finally { out.close(); } } Response response = new Response(); response.setMethod(method.toString()); response.setUrl(url.toString()); response.setStatusCode(request.getResponseCode()); response.setStatusMessage(request.getResponseMessage()); response.setHeaders(request.getHeaderFields()); InputStream inputStream = null; if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) { inputStream = request.getInputStream(); } else { inputStream = request.getErrorStream(); } boolean isBinary = false; if (inputStream != null) { StringBuilder responseBody = new StringBuilder(); String contentType = request.getContentType(); if (contentType != null) { if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml") && !contentType.startsWith("application/json")) { // assume binary isBinary = true; inputStream = new Base64InputStream(inputStream, true); // base64 encode } } BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); try { String line = null; while ((line = bufferedReader.readLine()) != null) { responseBody.append(line); } } finally { bufferedReader.close(); } response.setContentType(contentType); if (isBinary) { String content = responseBody.toString(); if (content.length() == 0) { response.setBinaryContent(new byte[0]); } else { response.setBinaryContent(Base64.decodeBase64(responseBody.toString())); } } else { response.setContent(responseBody.toString()); } } if (logger.isDebugEnabled()) { if (isBinary) { logger.debug("RESPONSE - binary response omitted"); } else { logger.debug("RESPONSE - " + response.toString()); } } return response; } finally { request.disconnect(); } }
From source file:com.flipzu.flipzu.FlipInterface.java
String postViaHttpsConnection(String path, String params) throws IOException { HttpsURLConnection c = null; InputStream is = null;//from www . j a va2 s . com OutputStream os = null; String respString = null; int rc; // String url = WSServerSecure + path; URL url = new URL(WSServerSecure + path); try { trustAllHosts(); c = (HttpsURLConnection) url.openConnection(); c.setHostnameVerifier(DO_NOT_VERIFY); c.setDoOutput(true); // Set the request method and headers c.setRequestMethod("POST"); c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); c.setRequestProperty("Content-Language", "en-US"); c.setRequestProperty("Accept-Encoding", "identity"); // Getting the output stream may flush the headers os = c.getOutputStream(); os.write(params.getBytes()); os.flush(); // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. rc = c.getResponseCode(); if (rc != HttpURLConnection.HTTP_OK) { throw new IOException("HTTP response code: " + rc); } is = c.getInputStream(); // Get the length and process the data int len = (int) c.getContentLength(); if (len > 0) { int actual = 0; int bytesread = 0; byte[] data = new byte[len]; while ((bytesread != len) && (actual != -1)) { actual = is.read(data, bytesread, len - bytesread); bytesread += actual; } respString = new String(data); } else { byte[] data = new byte[8192]; int ch; int i = 0; while ((ch = is.read()) != -1) { if (i < data.length) data[i] = ((byte) ch); i++; } respString = new String(data); } } catch (ClassCastException e) { debug.logW(TAG, "Not an HTTP URL"); throw new IllegalArgumentException("Not an HTTP URL"); } finally { if (is != null) is.close(); if (os != null) os.close(); if (c != null) c.disconnect(); } return respString; }
From source file:eu.faircode.netguard.ServiceJob.java
@Override public boolean onStartJob(JobParameters params) { Log.i(TAG, "Start job=" + params.getJobId()); new AsyncTask<JobParameters, Object, Object>() { @Override//ww w . ja va2s. co m protected JobParameters doInBackground(JobParameters... params) { Log.i(TAG, "Executing job=" + params[0].getJobId()); HttpsURLConnection urlConnection = null; try { String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); JSONObject json = new JSONObject(); json.put("device", Util.sha256(android_id, "")); json.put("product", Build.DEVICE); json.put("sdk", Build.VERSION.SDK_INT); json.put("country", Locale.getDefault().getCountry()); json.put("netguard", Util.getSelfVersionCode(ServiceJob.this)); try { json.put("store", getPackageManager().getInstallerPackageName(getPackageName())); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); json.put("store", null); } for (String name : params[0].getExtras().keySet()) json.put(name, params[0].getExtras().get(name)); urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection(); urlConnection.setConnectTimeout(cTimeOutMs); urlConnection.setReadTimeout(cTimeOutMs); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Content-type", "application/json"); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(json.toString().getBytes()); // UTF-8 out.flush(); int code = urlConnection.getResponseCode(); if (code != HttpsURLConnection.HTTP_OK) throw new IOException("HTTP " + code); InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream()); Log.i(TAG, "Response=" + Util.readString(isr).toString()); jobFinished(params[0], false); if ("rule".equals(params[0].getExtras().getString("type"))) { SharedPreferences history = getSharedPreferences("history", Context.MODE_PRIVATE); history.edit().putLong(params[0].getExtras().getString("package") + ":submitted", new Date().getTime()).apply(); } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); jobFinished(params[0], true); } finally { if (urlConnection != null) urlConnection.disconnect(); try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } return null; } }.execute(params); return true; }
From source file:com.gmt2001.TwitchAPIv5.java
@SuppressWarnings("UseSpecificCatch") private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) { JSONObject j = new JSONObject("{}"); InputStream i = null;/* w w w . ja v a2 s. com*/ String content = ""; try { URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.addRequestProperty("Accept", header_accept); c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded"); if (!clientid.isEmpty()) { c.addRequestProperty("Client-ID", clientid); } if (!oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } else { if (!this.oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } } c.setRequestMethod(type.name()); 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); } } if (c.getResponseCode() == 200) { i = c.getInputStream(); } else { i = c.getErrorStream(); } if (c.getResponseCode() == 204 || i == null) { content = "{}"; } else { // default to UTF-8, it'll probably be the best bet if there's // no charset specified. String charset = "utf-8"; String ct = c.getContentType(); if (ct != null) { String[] cts = ct.split(" *; *"); for (int idx = 1; idx < cts.length; ++idx) { String[] val = cts[idx].split("=", 2); if (val[0] == "charset" && val.length > 1) { charset = val[1]; } } } if ("gzip".equals(c.getContentEncoding())) { i = new GZIPInputStream(i); } content = IOUtils.toString(i, charset); } j = new JSONObject(content); fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content); } catch (Exception ex) { Throwable rootCause = ex; while (rootCause.getCause() != null && rootCause.getCause() != rootCause) { rootCause = rootCause.getCause(); } fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(), content); com.gmt2001.Console.debug .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage()); } finally { if (i != null) { try { i.close(); } catch (IOException ex) { fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content); com.gmt2001.Console.err.println("IOException: " + ex.getMessage()); } } } return j; }
From source file:git.egatuts.nxtremotecontroller.fragment.OnlineControllerFragment.java
public TokenRequester getTokenRequester() { final OnlineControllerFragment self = this; final TokenRequester requester = new TokenRequester(); requester.setRunnable(new Runnable() { @Override//from w ww .j av a2 s .c o m public void run() { String url = self.getPreferencesEditor().getString("preference_server_login", self.getString(R.string.preference_value_login)); try { URL location = new URL(url); HttpsURLConnection s_connection = null; HttpURLConnection connection = null; InputStream input; int responseCode; boolean isHttps = url.contains("https"); DataOutputStream writeStream; if (isHttps) { s_connection = (HttpsURLConnection) location.openConnection(); s_connection.setRequestMethod("POST"); writeStream = new DataOutputStream(s_connection.getOutputStream()); } else { connection = (HttpURLConnection) location.openConnection(); connection.setRequestMethod("POST"); writeStream = new DataOutputStream(connection.getOutputStream()); } StringBuilder urlParams = new StringBuilder(); urlParams.append("name=").append(Build.MODEL).append("&email=").append(self.getOwnerEmail()) .append("&host=").append(true).append("&longitude=").append(self.longitude) .append("&latitude=").append(self.latitude); writeStream.writeBytes(urlParams.toString()); writeStream.flush(); writeStream.close(); if (isHttps) { input = s_connection.getInputStream(); responseCode = s_connection.getResponseCode(); } else { input = connection.getInputStream(); responseCode = connection.getResponseCode(); } if (input != null) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input)); String line; String result = ""; while ((line = bufferedReader.readLine()) != null) { result += line; } input.close(); requester.finishRequest(result); } } catch (IOException e) { //e.printStackTrace(); requester.cancelRequest(e); } } }); return requester; }
From source file:com.photon.phresco.framework.commons.FrameworkUtil.java
public static int getHttpsResponse(String url) throws PhrescoException { URL httpsUrl;//from w w w. j a v a 2 s . c o m try { SSLContext ssl_ctx = SSLContext.getInstance("SSL"); TrustManager[] trust_mgr = get_trust_mgr(); ssl_ctx.init(null, trust_mgr, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory()); httpsUrl = new URL(url); HttpsURLConnection con = (HttpsURLConnection) httpsUrl.openConnection(); con.setHostnameVerifier(new HostnameVerifier() { // Guard against "bad hostname" errors during handshake. public boolean verify(String host, SSLSession sess) { return true; } }); return con.getResponseCode(); } catch (MalformedURLException e) { throw new PhrescoException(e); } catch (IOException e) { throw new PhrescoException(e); } catch (NoSuchAlgorithmException e) { throw new PhrescoException(e); } catch (KeyManagementException e) { throw new PhrescoException(e); } }
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public String requestASToken(Registration registration, String[] adds) throws IOException { String asToken = null;// w w w. j av a 2 s. c o m // Token Acquisition // Create a HTTP request as in the following prototype and send // it via TLS to the AM // // Token Acquisition // Create a HTTP request as in the following prototype and send // it via TLS to the AM // Request // POST /iam-services/0.1/oidc/am/token HTTP/1.1 URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION); HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection(); httpConTokenAcquisition.setDoOutput(true); httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConTokenAcquisition.setRequestProperty("Accept", "application/json"); // httpConTokenAcquisition.setRequestProperty("Authorization", // "Basic Base64(<c_id>:<c_secret>"); String auth = registration.c_id + ":" + registration.c_secret; String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes())); httpConTokenAcquisition.setRequestProperty("Authorization", authb); httpConTokenAcquisition.setRequestMethod("POST"); String requestBodyTokenAcquisition = "grant_type=client_credentials"; if (adds == null || adds.length == 0) { // no additions } else { if (adds.length % 2 == 0) { for (int i = 0; i < (adds.length - 1); i += 2) { requestBodyTokenAcquisition += "&"; requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8"); requestBodyTokenAcquisition += "="; requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8"); } } else { log.warn( "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds)); } } OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream(); outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes()); outTokenAcquisition.close(); int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode(); log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": " + responseCodeoutTokenAcquisition); if (responseCodeoutTokenAcquisition == 200) { // everything ok InputStream isTA = httpConTokenAcquisition.getInputStream(); byte[] bisTA = getBytesFromInputStream(isTA); String jsonResponseTA = new String(bisTA); log.info(jsonResponseTA); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisTA); JsonNode actualObj = mapper.readTree(jp); JsonNode access_token = actualObj.get("access_token"); if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) { log.error("access_token: " + access_token); } else { // ok so far // access_token provides a JWT structure // see Understanding JWT // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html log.info("access_token: " + access_token); // http://jwt.io/ // TODO verify signature (e.g., use Jose4J) // Note: currently we assume signature is fine.. we just fetch // "as_token" String[] decAT = access_token.textValue().split("\\."); if (decAT == null || decAT.length != 3) { log.error("Cannot build JWT tripple structure for " + access_token); } else { assert (decAT.length == 3); // JWT structure // decAT[0]; // header // decAT[1]; // payload // decAT[2]; // signature String decAT1 = new String(Base64.getDecoder().decode(decAT[1])); JsonParser jpas = factory.createParser(decAT1); JsonNode payload = mapper.readTree(jpas); JsonNode as_token = payload.get("as_token"); if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) { log.error("as_token: " + as_token); } else { log.info("as_token: " + as_token); asToken = as_token.textValue(); } } } } else { // error InputStream error = httpConTokenAcquisition.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConTokenAcquisition.disconnect(); return asToken; }
From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java
/** * Read response from {@link HttpsURLConnection} * /*from w ww . j a v a 2s .co m*/ * @param con HttpsURLConnection. * @return String content of the HTTP response. * @throws IOException */ private String readResponseHTTPS(HttpsURLConnection con) throws IOException { InputStream responseStream = null; String responseString = null; if (con.getResponseCode() >= 400) { responseStream = con.getErrorStream(); } else { responseStream = con.getInputStream(); } if (responseStream != null) { StringBuilder stringBuilder = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = responseStream.read(bytes)) != -1) { stringBuilder.append(new String(bytes, 0, len)); } if (!stringBuilder.toString().trim().isEmpty()) { responseString = stringBuilder.toString(); } } return responseString; }
From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java
/** * Send HTTP request using {@link HttpURLConnection} in JSON format to return {@link InputStream}. * //w w w . j a v a 2 s .co m * @param endPoint String End point URL. * @param httpMethod String HTTP method type (GET, POST, PUT etc.) * @param headersMap Map<String, String> Headers need to send to the end point. * @param requestFileName String File name of the file which contains request body data. * @param parametersMap Map<String, String> Additional parameters which is not predefined in the * properties file. * @return InputStream * @throws IOException * @throws XMLStreamException */ protected InputStream processForInputStreamHTTPS(String endPoint, String httpMethod, Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap, boolean isIgnoreHostVerification) throws IOException, JSONException { HttpsURLConnection httpsConnection = writeRequestHTTPS(endPoint, httpMethod, RestResponse.JSON_TYPE, headersMap, requestFileName, parametersMap, isIgnoreHostVerification); InputStream responseStream = null; if (httpsConnection.getResponseCode() >= 400) { responseStream = httpsConnection.getErrorStream(); } else { responseStream = httpsConnection.getInputStream(); } return responseStream; }