List of usage examples for javax.net.ssl HttpsURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java
/** * Validate the SafetyNet response using the Android Device Verification API. This API performs a validation check on * the JWS message returned from the SafetyNet service. * * <b>Important:</b> This use of the Android Device Verification API only validates that the provided JWS message was * received from the SafetyNet service. It <i>does not</i> verify that the payload data matches your original * compatibility check request./* ww w .j ava2s. c o m*/ * * @param jws * The output of {@link SafetyNetApi.AttestationResult#getJwsResult()}. * @param apiKey * The Android Device Verification API key * @return {@code true} if the provided JWS message was received from the SafetyNet service. * @throws SafetyNetError * if an error occurs while verifying the JSON Web Signature. */ public static boolean validate(@NonNull String jws, @NonNull String apiKey) throws SafetyNetError { try { URL verifyApiUrl = new URL(GOOGLE_VERIFICATION_URL + apiKey); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] defaultTrustManagers = trustManagerFactory.getTrustManagers(); TrustManager[] trustManagers = Arrays.copyOf(defaultTrustManagers, defaultTrustManagers.length + 1); trustManagers[defaultTrustManagers.length] = new GoogleApisTrustManager(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, null); HttpsURLConnection urlConnection = (HttpsURLConnection) verifyApiUrl.openConnection(); urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/json"); JSONObject requestJson = new JSONObject(); requestJson.put("signedAttestation", jws); byte[] outputInBytes = requestJson.toString().getBytes("UTF-8"); OutputStream os = urlConnection.getOutputStream(); os.write(outputInBytes); os.close(); urlConnection.connect(); InputStream is = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); for (String line = reader.readLine(), nl = ""; line != null; line = reader.readLine(), nl = "\n") { sb.append(nl).append(line); } return new JSONObject(sb.toString()).getBoolean("isValidSignature"); } catch (Exception e) { throw new SafetyNetError(e); } }
From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java
private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken) throws IOException, HttpResultException { HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection(); nection.setDoInput(true);/*from w ww . ja v a 2 s. co m*/ nection.setDoOutput(true); nection.setConnectTimeout(2000); nection.setReadTimeout(1000); nection.setRequestProperty("Content-Type", "application/json"); nection.setRequestProperty("Accept", "application/json"); nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME); if (accessToken != null) { nection.setRequestProperty("Authorization", "token " + accessToken); } OutputStream os = nection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(params.toString()); writer.flush(); writer.close(); os.close(); try { nection.connect(); int code = nection.getResponseCode(); if (code != HttpsURLConnection.HTTP_CREATED && code != HttpsURLConnection.HTTP_OK) { throw new HttpResultException(nection.getResponseCode(), nection.getResponseMessage()); } InputStream in = new BufferedInputStream(nection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); while (true) { String line = reader.readLine(); if (line == null) { break; } response.append(line); } try { return new JSONObject(response.toString()); } catch (JSONException e) { throw new IOException(e); } } finally { nection.disconnect(); } }
From source file:com.illusionaryone.GoogleURLShortenerAPIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress, String longURL) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;// w ww. j a v a2 s . co m HttpsURLConnection urlConn; String jsonRequest = ""; String jsonText = ""; try { jsonRequest = "{ 'longUrl': '" + longURL + "'}"; byte[] postRequest = jsonRequest.getBytes("UTF-8"); urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.addRequestProperty("Content-Length", String.valueOf(postRequest.length)); urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json"); urlConn.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"); urlConn.connect(); urlConn.getOutputStream().write(postRequest); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (UnsupportedEncodingException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "UnsupportedEncodingException", ex.getMessage(), jsonText); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } } return (jsonResult); }
From source file:com.longtime.ajy.support.weixin.HttpsKit.java
/** * ??Get/*w w w . j av a2 s . c o m*/ * * @param url * @return * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws IOException * @throws KeyManagementException */ public static String get(String url) {//throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException { InputStream in = null; HttpsURLConnection http = null; try { StringBuffer bufferRes = null; TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url); http = (HttpsURLConnection) urlGet.openConnection(); // http.setConnectTimeout(TIME_OUT_CONNECT); // ? --?? http.setReadTimeout(TIME_OUT_READ); http.setRequestMethod("GET"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } return bufferRes.toString(); } catch (Exception e) { logger.error(String.format("HTTP GET url=[%s] due to fail.", url), e); } finally { if (null != in) { try { in.close(); } catch (IOException e) { logger.error(String.format("HTTP GET url=[%s] close inputstream due to fail.", url), e); } } if (http != null) { // http.disconnect(); } } return StringUtils.EMPTY; }
From source file:org.sakaiproject.turnitin.util.TurnitinAPIUtil.java
public static InputStream callTurnitinReturnInputStream(String apiURL, Map<String, Object> parameters, String secretKey, int timeout, Proxy proxy, boolean isMultipart) throws TransientSubmissionException, SubmissionException { InputStream togo = null;/*from w w w . j a v a 2 s . c om*/ StringBuilder apiDebugSB = new StringBuilder(); if (!parameters.containsKey("fid")) { throw new IllegalArgumentException("You must to include a fid in the parameters"); } //if (!parameters.containsKey("gmttime")) { parameters.put("gmtime", getGMTime()); //} /** * Some debug logging */ if (log.isDebugEnabled()) { Set<Entry<String, Object>> ets = parameters.entrySet(); Iterator<Entry<String, Object>> it = ets.iterator(); while (it.hasNext()) { Entry<String, Object> entr = it.next(); log.debug("Paramater entry: " + entr.getKey() + ": " + entr.getValue()); } } List<String> sortedkeys = new ArrayList<String>(); sortedkeys.addAll(parameters.keySet()); String md5 = buildTurnitinMD5(parameters, secretKey, sortedkeys); HttpsURLConnection connection; String boundary = ""; try { connection = fetchConnection(apiURL, timeout, proxy); if (isMultipart) { Random rand = new Random(); //make up a boundary that should be unique boundary = Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); } log.debug("HTTPS Connection made to Turnitin"); OutputStream outStream = connection.getOutputStream(); if (isMultipart) { if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append("Starting Multipart TII CALL:\n"); } for (int i = 0; i < sortedkeys.size(); i++) { if (parameters.get(sortedkeys.get(i)) instanceof ContentResource) { ContentResource resource = (ContentResource) parameters.get(sortedkeys.get(i)); outStream.write( ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"pdata\"; filename=\"" + resource.getId() + "\"\r\n" + "Content-Type: " + resource.getContentType() + "\r\ncontent-transfer-encoding: binary" + "\r\n\r\n").getBytes()); //TODO this loads the doc into memory rather use the stream method byte[] content = resource.getContent(); if (content == null) { throw new SubmissionException("zero length submission!"); } outStream.write(content); outStream.write("\r\n".getBytes("UTF-8")); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append(sortedkeys.get(i)); apiDebugSB.append(" = ContentHostingResource: "); apiDebugSB.append(resource.getId()); apiDebugSB.append("\n"); } } else { if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append(sortedkeys.get(i)); apiDebugSB.append(" = "); apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString()); apiDebugSB.append("\n"); } outStream.write(encodeParam(sortedkeys.get(i), parameters.get(sortedkeys.get(i)).toString(), boundary).getBytes()); } } outStream.write(encodeParam("md5", md5, boundary).getBytes()); outStream.write(("--" + boundary + "--").getBytes()); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append("md5 = "); apiDebugSB.append(md5); apiDebugSB.append("\n"); apiTraceLog.debug(apiDebugSB.toString()); } } else { writeBytesToOutputStream(outStream, sortedkeys.get(0), "=", parameters.get(sortedkeys.get(0)).toString()); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append("Starting TII CALL:\n"); apiDebugSB.append(sortedkeys.get(0)); apiDebugSB.append(" = "); apiDebugSB.append(parameters.get(sortedkeys.get(0)).toString()); apiDebugSB.append("\n"); } for (int i = 1; i < sortedkeys.size(); i++) { writeBytesToOutputStream(outStream, "&", sortedkeys.get(i), "=", parameters.get(sortedkeys.get(i)).toString()); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append(sortedkeys.get(i)); apiDebugSB.append(" = "); apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString()); apiDebugSB.append("\n"); } } writeBytesToOutputStream(outStream, "&md5=", md5); if (apiTraceLog.isDebugEnabled()) { apiDebugSB.append("md5 = "); apiDebugSB.append(md5); apiTraceLog.debug(apiDebugSB.toString()); } } outStream.close(); togo = connection.getInputStream(); } catch (IOException t) { log.error("IOException making turnitin call.", t); throw new TransientSubmissionException("IOException making turnitin call.", t); } catch (ServerOverloadException t) { throw new TransientSubmissionException("Unable to submit the content data from ContentHosting", t); } return togo; }
From source file:com.longtime.ajy.support.weixin.HttpsKit.java
/** * ??Post/*from w w w .j a v a 2 s . co m*/ * * @param url * @param params * @return * @throws IOException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { OutputStream out = null; InputStream in = null; HttpsURLConnection http = null; try { StringBuffer bufferRes = null; TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url); http = (HttpsURLConnection) urlGet.openConnection(); // http.setConnectTimeout(TIME_OUT_CONNECT); // ? --?? http.setReadTimeout(TIME_OUT_READ); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); out = http.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } return bufferRes.toString(); } catch (Exception e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] due to fail.", url, params), e); } finally { if (null != out) { try { out.close(); } catch (IOException e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] close outputstream due to fail.", url, params), e); } } if (null != in) { try { in.close(); } catch (IOException e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url, params), e); } } if (http != null) { // http.disconnect(); } } return StringUtils.EMPTY; }
From source file:com.illusionaryone.GameWispAPI.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String methodType, String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; OutputStream outputStream = null; URL urlRaw;//www .j av a2s . co m HttpsURLConnection urlConn; String jsonText = ""; if (sAccessToken.length() == 0) { if (!noAccessWarning) { com.gmt2001.Console.err.println( "GameWispAPI: Attempting to use GameWisp API without key. Disable GameWisp module."); noAccessWarning = true; } JSONStringer jsonObject = new JSONStringer(); return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject() .endObject().toString())); } try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod(methodType); urlConn.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"); if (methodType.equals("POST")) { urlConn.setDoOutput(true); urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else { urlConn.addRequestProperty("Content-Type", "application/json"); } urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err .println("GameWispAPI::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "..."); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } } } return (jsonResult); }
From source file:xyz.karpador.godfishbot.commands.QuoteCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { try {//from ww w . j av a 2 s . c o m String cat = Main.Random.nextInt(2) == 0 ? "famous" : "movies"; URL url = new URL("https://andruxnet-random-famous-quotes.p.mashape.com/?cat=" + cat + "&count=1"); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("X-Mashape-Key", BotConfig.getInstance().getMashapeToken()); con.setRequestProperty("Accept", "application/json"); con.setReadTimeout(5000); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = br.readLine(); JSONObject resultJson = new JSONObject(result); String cmdResult = "" + resultJson.getString("quote") + " - " + resultJson.getString("author"); return new CommandResult(cmdResult); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; }
From source file:io.siddhi.doc.gen.extensions.githubclient.ContentsResponse.java
ContentsResponse(HttpsURLConnection connection) throws IOException { connection.setRequestProperty("Accept", "application/vnd.githubclient.v3." + mediaType()); status = connection.getResponseCode(); stream = (status == 200) ? connection.getInputStream() : connection.getErrorStream(); headers = connection.getHeaderFields(); contentsBodyReader = null;//from w w w. j a v a2 s. co m }
From source file:xyz.karpador.godfishbot.commands.TestLoveCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { if (params == null) return new CommandResult("Please submit two names."); String[] names = params.split(" "); if (names.length < 2) return new CommandResult("Please submit two names."); try {//from ww w .j a v a 2 s . co m URL url = new URL("https://love-calculator.p.mashape.com/getPercentage" + "?fname=" + names[0] + "&sname=" + names[1]); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("X-Mashape-Key", BotConfig.getInstance().getMashapeToken()); con.setRequestProperty("Accept", "application/json"); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = br.readLine(); JSONObject resultJson = new JSONObject(result); String cmdResult = names[0] + " and " + names[1] + " fit " + resultJson.getString("percentage") + "%.\n" + resultJson.getString("result"); return new CommandResult(cmdResult); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; }