List of usage examples for javax.net.ssl HttpsURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:ovh.tgrhavoc.aibot.RealmsUtil.java
private static String mcoapiGet(String address, YggdrasilSession session, ProxyData proxy) throws IOException { Proxy wrappedProxy = wrapProxy(proxy); HttpsURLConnection connection; if (wrappedProxy != null) connection = (HttpsURLConnection) new URL(address).openConnection(wrappedProxy); else// www. j a v a2 s.c om connection = (HttpsURLConnection) new URL(address).openConnection(); connection.addRequestProperty("Cookie", "user=" + session.getUsername() + ";version=1.7.2;sid=token:" + session.getAccessToken().toString(16) + ":" + session.getSelectedProfile().getId()); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.connect(); InputStream in = connection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read); return new String(out.toByteArray()); }
From source file:ke.co.tawi.babblesms.server.servlet.accountmngmt.Login.java
public static boolean validateCaptcha(String gRecaptchaResponse) throws IOException { if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) { return false; }/*from ww w .j a v a 2s.c om*/ try { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + postParams); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result System.out.println(response.toString()); //parse JSON response and return 'success' value JsonReader jsonReader = Json.createReader(new StringReader(response.toString())); JsonObject jsonObject = jsonReader.readObject(); jsonReader.close(); return jsonObject.getBoolean("success"); } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java
public static String[] getAccessTokens(final String[] requests) throws Exception { final String TAG = "getAccesTokens"; String code = requests[0];/*from w ww.ja v a 2 s. c om*/ String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET; String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0); URL url1 = new URL("https://api.quizlet.com/oauth/token"); HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection(); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // Add the Basic Authorization item conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s", URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"), URLEncoder.encode(Data.RedirectURI, "UTF-8")); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(payload); out.close(); if (conn.getResponseCode() / 100 >= 3) { Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: " + conn.getResponseMessage()); JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); String error = ""; r.beginObject(); while (r.hasNext()) { error += r.nextName() + r.nextString() + "\r\n"; } r.endObject(); r.close(); Log.e(TAG, "Error response for: " + url1 + " is " + error); throw new IOException("Response code: " + conn.getResponseCode()); } JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); try { String accessToken = null; String userId = null; s.beginObject(); while (s.hasNext()) { String name = s.nextName(); if (name.equals("access_token")) { accessToken = s.nextString(); } else if (name.equals("user_id")) { userId = s.nextString(); } else { s.skipValue(); } } s.endObject(); s.close(); return new String[] { accessToken, userId }; } catch (Exception e) { // Throw out JSON exception. it is unlikely to happen throw new RuntimeException(e); } finally { conn.disconnect(); } }
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse getWithBasicAuth(String Uri, String requestParameters, String userName, String password) throws IOException { if (Uri.startsWith("https://")) { String urlStr = Uri;/*from ww w . j av a2 s . com*/ if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); conn.setRequestProperty("Authorization", "Basic " + encode); 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(), 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:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType, String userName, String password) throws IOException { if (uri.startsWith("https://")) { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); conn.setRequestProperty("Authorization", "Basic " + encode); conn.setDoOutput(true); // Triggers POST. conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length)); conn.setUseCaches(false);/*from www . j ava2s . com*/ conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestQuery); conn.setReadTimeout(10000); conn.connect(); System.out.println(conn.getRequestMethod()); // Get the response 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(); } wr.flush(); wr.close(); conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:Main.java
/** * * @param url - String/*from w ww. ja v a 2 s . co m*/ * @param reqParam refer POST method * @param accessToken - String * @return ArrayList<String> 0: responseBody * 1: responseCode */ public static ArrayList<String> getResponse(String url, String reqParam, String accessToken) { StringBuilder response = null; StringBuilder urlBuilder = null; BufferedReader in = null; HttpsURLConnection con = null; ArrayList<String> responseList = new ArrayList<String>(); int responseCode = -1; try { response = new StringBuilder(); urlBuilder = new StringBuilder(); urlBuilder.append(url); urlBuilder.append("?").append(reqParam); urlBuilder.append("&access_token=").append(accessToken); URL urlObj = new URL(urlBuilder.toString()); con = (HttpsURLConnection) urlObj.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); con.setDoOutput(false); con.setRequestProperty("Authorization: Bearer", accessToken); in = new BufferedReader(new InputStreamReader(con.getInputStream())); responseCode = con.getResponseCode(); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } catch (Exception e) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); String inputLine = ""; try { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (responseCode == -1) { } else { System.out.println(response.toString()); } } finally { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } responseList.add(response.toString()); responseList.add(String.valueOf(responseCode)); return responseList; }
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);// www. j a v a 2 s . co 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.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse putWithBasicAuth(String uri, String requestQuery, String contentType, String userName, String password) throws IOException { if (uri.startsWith("https://")) { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); ;/* w w w. j a va2 s . co m*/ conn.setRequestProperty("Authorization", "Basic " + encode); conn.setDoOutput(true); // Triggers POST. conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length)); conn.setUseCaches(false); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestQuery); conn.setReadTimeout(10000); conn.connect(); // Get the response 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(); } wr.flush(); wr.close(); conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String userName, String password) throws IOException { if (uri.startsWith("https://")) { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); ;//from ww w . ja va 2 s. c o m conn.setRequestProperty("Authorization", "Basic " + encode); conn.setDoOutput(true); // Triggers POST. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length)); conn.setUseCaches(false); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestQuery); conn.setReadTimeout(10000); conn.connect(); System.out.println(conn.getRequestMethod()); // Get the response 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); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } wr.flush(); wr.close(); conn.disconnect(); } } return null; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call to get a new client credentials token, required for creating new account * //from ww w .j a v a 2 s.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; }