List of usage examples for javax.net.ssl HttpsURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:eu.siacs.conversations.ui.ServiceBrowserFragment.java
public static boolean exists(String URLName) { X509TrustManager trustManager = new X509TrustManager() { @Override/*from w ww. j ava 2 s. c om*/ public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE : This is where we can calculate the certificate's fingerprint, // show it to the user and throw an exception in case he doesn't like it } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }; // Create a trust manager that does not validate certificate chains X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager }; // Install the all-trusting trust manager SSLSocketFactory noSSLv3Factory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom()); } else { noSSLv3Factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory); } catch (GeneralSecurityException e) { } try { HttpsURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) URL url = new URL(URLName); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(noSSLv3Factory); con.setRequestProperty("Accept-Encoding", ""); //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier()); con.setHostnameVerifier(new NullHostNameVerifier(url.getHost())); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpsURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:com.microsoft.office365.connectmicrosoftgraph.ConnectUnitTests.java
@BeforeClass public static void getAccessTokenUsingPasswordGrant() throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException { URL url = new URL(TOKEN_ENDPOINT); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); String urlParameters = String.format( "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE, URLEncoder.encode(Constants.MICROSOFT_GRAPH_API_ENDPOINT_RESOURCE_ID, "UTF-8"), clientId, username, password);//from w ww . ja v a 2 s. c o m connection.setRequestMethod(REQUEST_METHOD); connection.setRequestProperty("Content-Type", CONTENT_TYPE); connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length)); connection.setDoOutput(true); DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.writeBytes(urlParameters); dataOutputStream.flush(); dataOutputStream.close(); connection.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JsonParser jsonParser = new JsonParser(); JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString()); accessToken = grantResponse.get("access_token").getAsString(); }
From source file:org.openhab.binding.whistle.internal.WhistleBinding.java
static private String GetData(URL obj, String authToken) throws Exception { HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add request headers and parameters con.setDoOutput(true);//from w w w . j a v a2 s.c om con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)"); con.setRequestProperty("X-Whistle-AuthToken", authToken); // System.out.println("Response Code : " + con.getResponseCode()); if (con.getResponseCode() != 200) { logger.error("Failed to get requested data, response code: '{}'", con.getResponseCode()); return null; } // Get the data BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String response = in.readLine(); in.close(); return response; }
From source file:com.illusionaryone.BTTVAPIv2.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;/*from w ww.j ava 2s . c om*/ HttpsURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/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(); 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.printStackTrace(ex); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } } return (jsonResult); }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
public static HttpsURLConnection createSecureConnection(URL url) throws IOException { HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " OCCAndroidSDK"); return connection; }
From source file:org.openhab.binding.whistle.internal.WhistleBinding.java
protected static String getAuthToken(String username, String password) throws Exception { logger.debug("Using username: '{}' / password: '{}'", username, password); URL obj = new URL(APIROOT + "tokens.json"); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add request headers and parameters con.setDoOutput(true);/* w ww . ja v a 2s. c om*/ con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)"); con.setRequestMethod("POST"); String urlParameters = "{\"password\":\"" + password + "\",\"email\":\"" + username + "\",\"app_id\":\"com.whistle.WhistleApp\"}"; DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); if (con.getResponseCode() != 200) { logger.error("Username / password combination didn't work. Failed to get AuthenticationToken"); return null; } // Read the buffer BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String response = in.readLine(); in.close(); // Parse the data and return the token JsonObject jobj = new Gson().fromJson(response, JsonObject.class); return jobj.get("token").getAsString(); }
From source file:com.ds.kaixin.Util.java
/** * http/*from w w w . ja v a2s.c o m*/ * * @param context * * @param requestURL * * @param httpMethod * GET POST * @param params * key-valuekeyvalueString * byte[] * @param photos * key-value keyfilename * valueInputStreambyte[] * InputStreamopenUrl * @return JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, ""); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }
From source file:com.scaniatv.TipeeeStreamAPIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;//from www.ja v a2s. c o m HttpsURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/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(); 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.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::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.debug .println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } } } return (jsonResult); }
From source file:com.kaixin.connect.Util.java
/** * http// w w w .jav a2 s. c o m * * @param context * * @param requestURL * * @param httpMethod * GET POST * @param params * key-valuekeyvalueStringbyte[] * @param photos * key-value keyfilename * valueInputStreambyte[] * InputStreamopenUrl * @return JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, ""); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }
From source file:cn.bidaround.ytcore.kaixin.KaixinUtil.java
/** * ??http/*ww w . ja va2s . c om*/ * * @param context * * @param requestURL * ?? * @param httpMethod * GET POST * @param params * key-value??key???value???Stringbyte[] * @param photos * key-value??? keyfilename * value????InputStreambyte[] * ?InputStreamopenUrl? * @return ?JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); // for (String key : params.keySet()) { // if (params.getByteArray(key) != null) { // dataparams.putByteArray(key, params.getByteArray(key)); // } // } String BOUNDARY = KaixinUtil.md5(String.valueOf(System.currentTimeMillis())); // ? String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, "?"); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }