List of usage examples for javax.net.ssl HttpsURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:Main.java
public static String executeHttpsPost(String url, String data, InputStream key) { HttpsURLConnection localHttpsURLConnection = null; try {/*from w w w . j a v a 2 s. c o m*/ URL localURL = new URL(url); localHttpsURLConnection = (HttpsURLConnection) localURL.openConnection(); localHttpsURLConnection.setRequestMethod("POST"); localHttpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); localHttpsURLConnection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); localHttpsURLConnection.setRequestProperty("Content-Language", "en-US"); localHttpsURLConnection.setUseCaches(false); localHttpsURLConnection.setDoInput(true); localHttpsURLConnection.setDoOutput(true); localHttpsURLConnection.connect(); Certificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates(); byte[] arrayOfByte1 = new byte[294]; DataInputStream localDataInputStream = new DataInputStream(key); localDataInputStream.readFully(arrayOfByte1); localDataInputStream.close(); Certificate localCertificate = arrayOfCertificate[0]; PublicKey localPublicKey = localCertificate.getPublicKey(); byte[] arrayOfByte2 = localPublicKey.getEncoded(); for (int i = 0; i < arrayOfByte2.length; i++) { if (arrayOfByte2[i] != arrayOfByte1[i]) throw new RuntimeException("Public key mismatch"); } DataOutputStream localDataOutputStream = new DataOutputStream( localHttpsURLConnection.getOutputStream()); localDataOutputStream.writeBytes(data); localDataOutputStream.flush(); localDataOutputStream.close(); InputStream localInputStream = localHttpsURLConnection.getInputStream(); BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream)); StringBuffer localStringBuffer = new StringBuffer(); String str1; while ((str1 = localBufferedReader.readLine()) != null) { localStringBuffer.append(str1); localStringBuffer.append('\r'); } localBufferedReader.close(); return localStringBuffer.toString(); } catch (Exception localException) { byte[] arrayOfByte1; localException.printStackTrace(); return null; } finally { if (localHttpsURLConnection != null) localHttpsURLConnection.disconnect(); } }
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); nection.setDoOutput(true);/* w w w . j av a 2 s . c om*/ 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.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call to get a new client credentials token, required for creating new account * /* w w w. jav a 2s . com*/ * @param url * @param clientCredentialsToken * @param httpMethod * @param httpBody * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws ProtocolException * @throws JSONException */ public static String getClientCredentialsResponse(Context context, String url, String clientCredentialsToken, String httpMethod, Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException { boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url))); trustAllHosts(); connection.setHostnameVerifier(DO_NOT_VERIFY); connection.setRequestMethod(httpMethod); connection.setDoOutput(true); connection.setDoInput(true); String authValue = "Bearer " + clientCredentialsToken; connection.setRequestProperty("Authorization", authValue); connection.connect(); if (!httpBody.isEmpty()) { OutputStream os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); } try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (FileNotFoundException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) return response; }
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse deleteWithBasicAuth(String uri, String contentType, String userName, String password) throws IOException { if (uri.startsWith("https://")) { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("DELETE"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); ;/*from ww w. j a va 2 s . co m*/ conn.setRequestProperty("Authorization", "Basic " + encode); if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); conn.connect(); StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call for logging in/*from w ww . j a v a 2s .c o m*/ * * @param httpBody * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws JSONException */ public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException { String response = ""; URL url = new URL(WebServiceAuthProvider.tokenURL()); trustAllHosts(); HttpsURLConnection connection = createSecureConnection(url); connection.setHostnameVerifier(DO_NOT_VERIFY); String authString = "mobile_android:secret"; String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", authValue); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); OutputStream os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (MalformedURLException e) { LoggingUtils.e(LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), null); } catch (IOException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } return response; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call for logging out/*www . ja va2 s . c o m*/ * * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws JSONException */ public static String getLogoutResponse(Context context) throws MalformedURLException, IOException, JSONException { // Refresh if necessary if (WebServiceAuthProvider.tokenExpiredHint(context)) { WebServiceAuthProvider.refreshAccessToken(context); } boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } URL url = new URL(urlForLogout(context)); HttpsURLConnection connection = createSecureConnection(url); trustAllHosts(); connection.setHostnameVerifier(DO_NOT_VERIFY); String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token"); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", authValue); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); try { LoggingUtils.d(LOG_TAG, "LogoutResponse" + connection.toString()); response = readFromStream(connection.getInputStream()); } catch (MalformedURLException e) { LoggingUtils.e(LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), null); } catch (IOException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) return response; }
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;/*from ww w .j ava 2 s.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:org.sakaiproject.contentreview.turnitin.util.TurnitinAPIUtil.java
private static HttpsURLConnection fetchConnection(String apiURL, int timeout, Proxy proxy) throws MalformedURLException, IOException, ProtocolException { HttpsURLConnection connection; URL hostURL = new URL(apiURL); if (proxy == null) { connection = (HttpsURLConnection) hostURL.openConnection(); } else {//w w w . j a v a 2 s . c o m connection = (HttpsURLConnection) hostURL.openConnection(proxy); } // This actually turns into a POST since we are writing to the // resource body. ( You can see this in Webscarab or some other HTTP // interceptor. connection.setRequestMethod("GET"); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setDoOutput(true); connection.setDoInput(true); return connection; }
From source file:com.illusionaryone.GameWispAPIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String methodType, String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; OutputStream outputStream = null; URL urlRaw;/*from w ww .jav a 2 s . c om*/ HttpsURLConnection urlConn; String jsonText = ""; if (sAccessToken.length() == 0) { if (!noAccessWarning) { com.gmt2001.Console.err.println( "GameWispAPIv1: Attempting to use GameWisp API without key. Disabling the GameWisp module."); PhantomBot.instance().getDataStore().set("modules", "./handlers/gameWispHandler.js", "false"); 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 PhantomBotJ/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("GameWispAPIv1::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "..."); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::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("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } } return (jsonResult); }
From source file:com.longtime.ajy.support.weixin.HttpsKit.java
/** * ??Get/*from w w w .j av a2 s.c om*/ * * @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; }