List of usage examples for javax.net.ssl HttpsURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:org.liberty.android.fantastischmemo.downloader.google.GoogleAccountActivity.java
@Override protected String[] getAccessTokens(final String[] requests) throws IOException { String code = requests[0];//from ww w . j a v a 2 s. c om 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:in.rab.ordboken.NeClient.java
private void loginMainSite() throws IOException, LoginException { ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>(); data.add(new BasicNameValuePair("_save_loginForm", "true")); data.add(new BasicNameValuePair("redir", "/success")); data.add(new BasicNameValuePair("redirFail", "/fail")); data.add(new BasicNameValuePair("userName", mUsername)); data.add(new BasicNameValuePair("passWord", mPassword)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data); URL url = new URL("https://www.ne.se/user/login.jsp"); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setInstanceFollowRedirects(false); https.setFixedLengthStreamingMode((int) entity.getContentLength()); https.setDoOutput(true);//w w w .j a v a2 s.c o m try { OutputStream output = https.getOutputStream(); entity.writeTo(output); output.close(); Integer response = https.getResponseCode(); if (response != 302) { throw new LoginException("Unexpected response: " + response); } String location = https.getHeaderField("Location"); if (!location.contains("/success")) { throw new LoginException("Failed to login"); } } finally { https.disconnect(); } }
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public Registration requestRegistrationAS() throws IOException { String clientName = "opPostmanTestRS"; // CLIENT_NAME_PREFIX + // System.currentTimeMillis(); String clientCredentials = "client_credentials"; String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\"" + clientCredentials + "\"], \"id_token_signed_response_alg\":\"" + "HS256" + "\"}"; // Registration URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AS); HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection(); httpConRegistration.setDoOutput(true); httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConRegistration.setRequestProperty("Content-Type", "application/json"); httpConRegistration.setRequestProperty("Accept", "application/json"); httpConRegistration.setRequestMethod("POST"); OutputStream outRegistration = httpConRegistration.getOutputStream(); outRegistration.write(requestBodyRegistration.getBytes()); outRegistration.close();/*from ww w. j a va 2 s .c o m*/ int responseCodeRegistration = httpConRegistration.getResponseCode(); log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration); if (responseCodeRegistration == 201) { // everything ok InputStream isR = httpConRegistration.getInputStream(); byte[] bisR = getBytesFromInputStream(isR); String jsonResponseRegistration = new String(bisR); log.info(jsonResponseRegistration); // extract the value of client_id (this value is called <c_id>in // the following) and the value of client_secret (called // <c_secret> in the following) from the JSON response ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisR); JsonNode actualObj = mapper.readTree(jp); JsonNode c_id = actualObj.get("client_id"); JsonNode c_secret = actualObj.get("client_secret"); if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null || c_secret.getNodeType() != JsonNodeType.STRING) { log.error("client_id: " + c_id); log.error("client_secret: " + c_secret); } else { // ok so far // Store <c_id> and <c_secret> for use during the token // acquisition log.info("client_id: " + c_id); log.info("client_secret: " + c_secret); return new Registration(c_id.textValue(), c_secret.textValue()); } } else { // error InputStream error = httpConRegistration.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConRegistration.disconnect(); return null; }
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public Registration requestRegistrationAM() throws IOException { Registration registration = null;//from ww w . j a va 2s . co m String clientName = CLIENT_NAME_PREFIX + System.currentTimeMillis(); String clientCredentials = "client_credentials"; String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\"" + clientCredentials + "\"]}"; // Registration URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AM); HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection(); httpConRegistration.setDoOutput(true); httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConRegistration.setRequestProperty("Content-Type", "application/json"); httpConRegistration.setRequestProperty("Accept", "application/json"); httpConRegistration.setRequestMethod("POST"); OutputStream outRegistration = httpConRegistration.getOutputStream(); outRegistration.write(requestBodyRegistration.getBytes()); outRegistration.close(); int responseCodeRegistration = httpConRegistration.getResponseCode(); log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration); if (responseCodeRegistration == 201) { // everything ok InputStream isR = httpConRegistration.getInputStream(); byte[] bisR = getBytesFromInputStream(isR); String jsonResponseRegistration = new String(bisR); log.info(jsonResponseRegistration); // extract the value of client_id (this value is called <c_id>in // the following) and the value of client_secret (called // <c_secret> in the following) from the JSON response ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisR); JsonNode actualObj = mapper.readTree(jp); JsonNode c_id = actualObj.get("client_id"); JsonNode c_secret = actualObj.get("client_secret"); if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null || c_secret.getNodeType() != JsonNodeType.STRING) { log.error("client_id: " + c_id); log.error("client_secret: " + c_secret); } else { // ok so far // Store <c_id> and <c_secret> for use during the token // acquisition log.info("client_id: " + c_id); log.info("client_secret: " + c_secret); registration = new Registration(c_id.textValue(), c_secret.textValue()); } } else { // error InputStream error = httpConRegistration.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConRegistration.disconnect(); return registration; }
From source file:httpRequests.GetPost.java
private void sendPost() throws Exception { String url = "https://selfsolve.apple.com/wcResults.do"; 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 urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; // Send post request con.setDoOutput(true);/*from w ww .j a v a 2 s . c o m*/ DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); 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()); }
From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java
public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType) throws IOException { URL obj = new URL(backEnd); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); if (!your_session_id.equals("")) { con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id); }//w ww . j a v a 2 s .co m if (!contentType.equals("")) { con.setRequestProperty("Content-Type", contentType); } con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(payload); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if (your_session_id.equals("")) { String session_id = response.substring((response.lastIndexOf(":") + 3), (response.lastIndexOf("}") - 2)); return session_id; } else if (your_session_id.equals("header")) { return con.getHeaderField("Set-Cookie"); } return response.toString(); } return null; }
From source file:org.whispersystems.textsecure.push.PushServiceSocket.java
private void uploadExternalFile(String method, String url, byte[] data) throws IOException { URL uploadUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection(); connection.setDoOutput(true);// w w w . j a v a 2 s.c om connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.connect(); try { OutputStream out = connection.getOutputStream(); out.write(data); out.close(); if (connection.getResponseCode() != 200) { throw new IOException( "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } }
From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java
private int processPostRequest(URL url, byte[] data, String contentType, String keyStore, String keyStorePassword) throws GeneralSecurityException, IOException { SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword); HttpsURLConnection con; con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(sslFactory); con.setDoOutput(true);/*from w ww . j a v a2s . c o m*/ con.setRequestMethod("POST"); con.addRequestProperty("x-ms-version", "2014-04-01"); con.setRequestProperty("Content-Length", String.valueOf(data.length)); con.setRequestProperty("Content-Type", contentType); DataOutputStream requestStream = new DataOutputStream(con.getOutputStream()); requestStream.write(data); requestStream.flush(); requestStream.close(); return con.getResponseCode(); }
From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java
private int getMsLayerCount(String url) { int cnt = -1; try {//from www . java2s . c om URL obj = new URL(url + "/query"); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add request header con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); con.setRequestProperty("Accept", "text/plain"); String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly=" + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result String jsonString = response.toString(); JSONTokener tokener = new JSONTokener(jsonString); JSONObject root = new JSONObject(tokener); cnt = root.getInt("count"); } catch (Exception e) { cnt = -2; } finally { return cnt; } }
From source file:com.nadmm.airports.notams.NotamService.java
private void fetchNotams(String icaoCode, File notamFile) throws IOException { String params = String.format(NOTAM_PARAM, icaoCode); HttpsURLConnection conn = (HttpsURLConnection) NOTAM_URL.openConnection(); conn.setRequestProperty("Connection", "close"); conn.setDoInput(true);//from w w w.jav a 2 s . com conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(30 * 1000); conn.setReadTimeout(30 * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(params.length())); // Write out the form parameters as the request body OutputStream faa = conn.getOutputStream(); faa.write(params.getBytes("UTF-8")); faa.close(); int response = conn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { // Request was successful, parse the html to extract notams InputStream in = conn.getInputStream(); ArrayList<String> notams = parseNotamsFromHtml(in); in.close(); // Write the NOTAMS to the cache file BufferedOutputStream cache = new BufferedOutputStream(new FileOutputStream(notamFile)); for (String notam : notams) { cache.write(notam.getBytes()); cache.write('\n'); } cache.close(); } }