List of usage examples for javax.net.ssl HttpsURLConnection getInputStream
public InputStream getInputStream() throws IOException
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 w w . ja va 2 s . c om 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:org.wso2.carbon.identity.authenticator.PushAuthentication.java
/** * Prompt for a login and an OTP.//from w w w. jav a2s . com */ public JSONObject pushAuthenticate(String userId) throws AuthenticationFailedException { String urlParameters = null; JSONObject json = null; HttpsURLConnection conn = null; InputStream is = null; try { urlParameters = "action=pushAuthenticate" + "&serviceId=" + URLEncoder.encode("" + serviceId, InweboConstants.ENCODING) + "&userId=" + URLEncoder.encode(userId, InweboConstants.ENCODING) + "&format=json"; if (this.context == null) { this.context = setHttpsClientCert(this.p12file, this.p12password); } SSLSocketFactory sslsocketfactory = context.getSocketFactory(); URL url = new URL(urlString + urlParameters); conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(sslsocketfactory); conn.setRequestMethod("GET"); is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, InweboConstants.ENCODING)); JSONParser parser = new JSONParser(); json = (JSONObject) parser.parse(br); } catch (UnsupportedEncodingException e) { throw new AuthenticationFailedException("Error while encoding the URL" + e.getMessage(), e); } catch (MalformedURLException e) { throw new AuthenticationFailedException("Error while creating the URL" + e.getMessage(), e); } catch (ParseException e) { throw new AuthenticationFailedException("Error while parsing the json object" + e.getMessage(), e); } catch (Exception e) { throw new AuthenticationFailedException("Error while pushing authentication" + e.getMessage(), e); } finally { if (conn != null) { conn.disconnect(); } try { if (is != null) { is.close(); } } catch (IOException e) { throw new AuthenticationFailedException("Error while closing stream" + e.getMessage(), e); } } return json; }
From source file:org.wso2.carbon.sample.service.EventsManagerService.java
public String performPostCall(String requestURL, Map<String, String> postDataParams) throws HttpException, IOException { URL url;//from w ww . jav a 2 s. c o m String response = ""; url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } else { response = ""; throw new HttpException(responseCode + ""); } return response; }
From source file:org.liberty.android.fantastischmemo.downloader.google.GoogleAccountActivity.java
@Override protected String[] getAccessTokens(final String[] requests) throws IOException { String code = requests[0];// ww w .j a v a 2 s . co m URL url1 = new URL("https://accounts.google.com/o/oauth2/token"); HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection(); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String payload = String.format("code=%s&client_id=%s&client_secret=%s&redirect_uri=%s&grant_type=%s", URLEncoder.encode(code, "UTF-8"), URLEncoder.encode(AMEnv.GOOGLE_CLIENT_ID, "UTF-8"), URLEncoder.encode(AMEnv.GOOGLE_CLIENT_SECRET, "UTF-8"), URLEncoder.encode(AMEnv.GOOGLE_REDIRECT_URI, "UTF-8"), URLEncoder.encode("authorization_code", "UTF-8")); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(payload); out.close(); String s = new String(IOUtils.toByteArray(conn.getInputStream())); try { JSONObject jsonObject = new JSONObject(s); String accessToken = jsonObject.getString("access_token"); //String refreshToken= jsonObject.getString("refresh_token"); return new String[] { accessToken }; } catch (JSONException e) { // Throw out JSON exception. it is unlikely to happen throw new RuntimeException(e); } }
From source file:Main.java
public static String executeHttpsPost(String url, String data, InputStream key) { HttpsURLConnection localHttpsURLConnection = null; try {//w w w . jav 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.wso2.carbon.integration.common.tests.JaggeryServerTest.java
/** * Sending the request and getting the response * @param Uri - request url/*from www .j av a 2 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:learn.encryption.ssl.SSLContext_Https.java
/** * Post??web??,?utf-8/*from w w w.j a v a2 s .co m*/ * * ?UTF8 * * @param actionUrl * @param params * @param timeout * @return * @throws InvalidParameterException * @throws NetWorkException * @throws IOException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws Exception */ public static String post(String url, Map<String, String> params, int timeout) throws IOException, IllegalArgumentException, IllegalAccessException { if (url == null || url.equals("")) throw new IllegalArgumentException("url "); if (params == null) throw new IllegalArgumentException("params ?"); if (url.indexOf('?') > 0) { url = url + "&token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE="; } else { url = url + "?token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE="; } String sb2 = ""; String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; // try { URL uri = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) uri.openConnection(); // conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); SSLSocketFactory ssf = sslContext.getSocketFactory(); conn.setSSLSocketFactory(ssf); conn.setHostnameVerifier(HOSTNAME_VERIFIER); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes("UTF-8")); InputStream in = null; byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); int res = conn.getResponseCode(); if (res == 200) { in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String line = ""; for (line = br.readLine(); line != null; line = br.readLine()) { sb2 = sb2 + line; } } outStream.close(); conn.disconnect(); return sb2; }
From source file:org.wso2.carbon.identity.authenticator.PushResult.java
/** * validate push result// www . j a v a 2 s . c om */ public JSONObject checkPushResult(String userId, String sessionId) throws AuthenticationFailedException { String urlParameters = null; JSONObject json = null; HttpsURLConnection conn = null; InputStream is = null; try { urlParameters = "action=checkPushResult" + "&serviceId=" + URLEncoder.encode("" + serviceId, InweboConstants.ENCODING) + "&userId=" + URLEncoder.encode(userId, InweboConstants.ENCODING) + "&sessionId=" + URLEncoder.encode(sessionId, InweboConstants.ENCODING) + "&format=json"; if (this.context == null) { this.context = PushAuthentication.setHttpsClientCert(this.p12file, this.p12password); } SSLSocketFactory sslsocketfactory = context.getSocketFactory(); URL url = new URL(urlString + urlParameters); conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(sslsocketfactory); conn.setRequestMethod("GET"); is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, InweboConstants.ENCODING)); JSONParser parser = new JSONParser(); json = (JSONObject) parser.parse(br); } catch (UnsupportedEncodingException e) { throw new AuthenticationFailedException("Error while encoding the URL" + e.getMessage(), e); } catch (MalformedURLException e) { throw new AuthenticationFailedException("Error while creating the URL" + e.getMessage(), e); } catch (IOException e) { throw new AuthenticationFailedException("Error while creating the connection" + e.getMessage(), e); } catch (ParseException e) { throw new AuthenticationFailedException("Error while parsing the json object" + e.getMessage(), e); } catch (Exception e) { throw new AuthenticationFailedException("Error while pushing authentication" + e.getMessage(), e); } finally { if (conn != null) { conn.disconnect(); } try { if (is != null) { is.close(); } } catch (IOException e) { throw new AuthenticationFailedException("Error while closing stream" + e.getMessage(), e); } } return json; }
From source file:hudson.plugins.pushover.PushoverApi.java
/** * Sends a raw bit of text via POST to PushoverApi. * * @param message//from w ww .jav a 2s . c o m * @return JSON reply from PushoverApi. * @throws IOException */ private String sendToPushover(String message) throws IOException { URL pushoverUrl = new URL(PUSHOVER_URL); HttpsURLConnection connection = (HttpsURLConnection) ProxyConfiguration.open(pushoverUrl); connection.setDoOutput(true); connection.setDoInput(true); OutputStream outputStream = null; try { outputStream = connection.getOutputStream(); outputStream.write(message.getBytes(Charset.forName("UTF-8"))); } finally { if (outputStream != null) { outputStream.close(); } } StringBuffer ret = new StringBuffer(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) ret.append(inputLine); } finally { in.close(); } return ret.toString(); }
From source file:com.fastbootmobile.twofactorauthdemo.MainActivity.java
protected void registerWithBackend() { final SharedPreferences pref = this.getSharedPreferences(OwnPushClient.PREF_PUSH, Context.MODE_PRIVATE); Thread httpThread = new Thread(new Runnable() { private String TAG = "httpThread"; private String ENDPOINT = "https://otp.demo.ownpush.com/push/register"; @Override/*from ww w .ja va 2s .c o m*/ public void run() { URL urlObj; try { urlObj = new URL(ENDPOINT); String install_id = pref.getString(OwnPushClient.PREF_PUBLIC_KEY, null); if (install_id == null) { return; } String mPostData = "push_id=" + install_id; HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); con.setRequestProperty("Accept", "*/*"); con.setDoInput(true); con.setRequestMethod("POST"); con.getOutputStream().write(mPostData.getBytes()); con.connect(); int http_status = con.getResponseCode(); if (http_status != 200) { Log.e(TAG, "ERROR IN HTTP REPONSE : " + http_status); return; } InputStream stream; stream = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String data = sb.toString(); if (data.contains("device_uid")) { JSONObject json = new JSONObject(data); String device_id = json.getString("device_uid"); pref.edit().putString("device_uid", device_id).commit(); Log.d(TAG, "GOT DEVICE UID OF " + device_id); mHandler.post(new Runnable() { @Override public void run() { updateUI(); } }); } } catch (Exception e) { e.printStackTrace(); } } }); httpThread.start(); }