List of usage examples for javax.net.ssl HttpsURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java
/** * This method is used to do a https post request * * @param url request url// w ww. j a va 2 s . c om * @param payload Content of the post request * @param sessionId sessionId for authentication * @param contentType content type of the post request * @return response * @throws java.io.IOException - Throws this when failed to fulfill a https post request */ public String doPostHttps(String url, String payload, String sessionId, String contentType) throws IOException { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); if (!sessionId.equals("")) { con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId); } 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 (sessionId.equals("")) { String session_id = response.substring((response.lastIndexOf(":") + 3), (response.lastIndexOf("}") - 2)); return session_id; } else if (sessionId.equals("header")) { return con.getHeaderField("Set-Cookie"); } return response.toString(); } return null; }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public 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 ww w . ja va 2s. co 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:xin.nic.sdk.registrar.util.HttpUtil.java
/** * ??HTTPS GET//ww w .j a v a 2 s . c om * * @param url URL * @return */ public static HttpResp doHttpsGet(URL url) { HttpsURLConnection conn = null; InputStream inputStream = null; Reader reader = null; try { // ???httphttps String protocol = url.getProtocol(); if (!PROTOCOL_HTTPS.equals(protocol)) { throw new XinException("xin.error.url", "?https"); } // conn = (HttpsURLConnection) url.openConnection(); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, tmArr, new SecureRandom()); conn.setSSLSocketFactory(sc.getSocketFactory()); // ? conn.setConnectTimeout(connTimeout); conn.setReadTimeout(readTimeout); conn.setDoOutput(true); conn.setDoInput(true); // UserAgent conn.setRequestProperty("User-Agent", "java-sdk"); // ? conn.connect(); // ? inputStream = conn.getInputStream(); reader = new InputStreamReader(inputStream, charset); BufferedReader bufferReader = new BufferedReader(reader); StringBuilder stringBuilder = new StringBuilder(); String inputLine = ""; while ((inputLine = bufferReader.readLine()) != null) { stringBuilder.append(inputLine); stringBuilder.append("\n"); } // HttpResp resp = new HttpResp(); resp.setStatusCode(conn.getResponseCode()); resp.setStatusPhrase(conn.getResponseMessage()); resp.setContent(stringBuilder.toString()); // return resp; } catch (MalformedURLException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } catch (IOException e) { throw new XinException("xin.error.http", String.format("IOException:%s", e.getMessage())); } catch (KeyManagementException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } catch (NoSuchAlgorithmException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new XinException("xin.error.url", "url:" + url + ", reader"); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new XinException("xin.error.url", "url:" + url + ", ?"); } } // quietClose(conn); } }
From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java
private HttpsURLConnection createHttpUrlConnection(URL url) throws Exception { HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new TrustAllHosts()); conn.setSSLSocketFactory(TrustAllCerts.createInsecureSslContext().getSocketFactory()); conn.setInstanceFollowRedirects(false); String credentials = TEST_USERNAME + ":" + TEST_PASSWORD; conn.setRequestProperty("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes())); return conn;//from w ww . jav a 2 s . co m }
From source file:android.locationprivacy.algorithm.Webservice.java
@Override public Location obfuscate(Location location) { // We do it this way to run network connection in main thread. This // way is not the normal one and does not comply to best practices, // but the main thread must wait for the obfuscation service reply anyway. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);//from w w w .j a v a2s.c o m final String HOST_ADDRESS = configuration.getString("host"); String username = configuration.getString("username"); String password = configuration.getString("secret_password"); Location newLoc = new Location(location); double lat = location.getLatitude(); double lon = location.getLongitude(); String urlString = HOST_ADDRESS; urlString += "?lat=" + lat; urlString += "&lon=" + lon; URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { Log.e(TAG, "Error: could not build URL"); Log.e(TAG, e.getMessage()); return null; } HttpsURLConnection connection = null; JSONObject json = null; InputStream is = null; try { connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); connection.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP)); is = connection.getInputStream(); } catch (IOException e) { Log.e(TAG, "Error while connectiong to " + url.toString()); Log.e(TAG, e.getMessage()); return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { String line = reader.readLine(); System.out.println("Line " + line); json = new JSONObject(line); newLoc.setLatitude(json.getDouble("lat")); newLoc.setLongitude(json.getDouble("lon")); } catch (IOException e) { Log.e(TAG, "Error: could not read from BufferedReader"); Log.e(TAG, e.getMessage()); return null; } catch (JSONException e) { Log.e(TAG, "Error: could not read from JSON"); Log.e(TAG, e.getMessage()); return null; } connection.disconnect(); return newLoc; }
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();/* www .jav a 2 s. co 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 w w w . j ava 2 s .c o 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:org.wso2.carbon.identity.authenticator.mepin.MepinTransactions.java
private String postRequest(String url, String query, String username, String password) throws IOException { String authStr = username + ":" + password; String encoding = new String(Base64.encodeBase64(authStr.getBytes())); String responseString = ""; HttpsURLConnection connection = null; BufferedReader br;/*from w w w . j a va2 s . c om*/ StringBuilder sb; String line; try { connection = (HttpsURLConnection) new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty(MepinConstants.HTTP_ACCEPT_CHARSET, MepinConstants.CHARSET); connection.setRequestProperty(MepinConstants.HTTP_CONTENT_TYPE, MepinConstants.HTTP_POST_CONTENT_TYPE); connection.setRequestProperty(MepinConstants.HTTP_AUTHORIZATION, MepinConstants.HTTP_AUTHORIZATION_BASIC + encoding); OutputStream output = connection.getOutputStream(); output.write(query.getBytes(MepinConstants.CHARSET)); int status = connection.getResponseCode(); if (log.isDebugEnabled()) { log.debug("MePIN Response Code :" + status); } switch (status) { case 200: br = new BufferedReader(new InputStreamReader(connection.getInputStream())); sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); responseString = sb.toString(); break; case 201: case 400: case 403: case 404: case 500: br = new BufferedReader(new InputStreamReader(connection.getInputStream())); sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); responseString = sb.toString(); if (log.isDebugEnabled()) { log.debug("MePIN Response :" + responseString); } return MepinConstants.FAILED; } } catch (IOException e) { if (connection.getErrorStream() != null) { br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); responseString = sb.toString(); if (log.isDebugEnabled()) { log.debug("MePIN Response :" + responseString); } return MepinConstants.FAILED; } } finally { connection.disconnect(); } if (log.isDebugEnabled()) { log.debug("MePIN Response :" + responseString); } return responseString; }
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 w w.ja v a 2 s . co 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:online.privacy.PrivacyOnlineApiRequest.java
private JSONObject makeAPIRequest(String method, String endPoint, String jsonPayload) throws IOException, JSONException { InputStream inputStream = null; OutputStream outputStream = null; String apiUrl = "https://api.privacy.online"; String apiKey = this.context.getString(R.string.privacy_online_api_key); String keyString = "?key=" + apiKey; int payloadSize = jsonPayload.length(); try {//from w ww .jav a 2 s .co m URL url = new URL(apiUrl + endPoint + keyString); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // Sec 5 second connect/read timeouts connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/json"); if (payloadSize > 0) { connection.setDoInput(true); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(payloadSize); } // Initiate the connection connection.connect(); // Write the payload if there is one. if (payloadSize > 0) { outputStream = connection.getOutputStream(); outputStream.write(jsonPayload.getBytes("UTF-8")); } // Get the response code ... int responseCode = connection.getResponseCode(); Log.e(LOG_TAG, "Response code: " + responseCode); switch (responseCode) { case HttpsURLConnection.HTTP_OK: inputStream = connection.getInputStream(); break; case HttpsURLConnection.HTTP_FORBIDDEN: inputStream = connection.getErrorStream(); break; case HttpURLConnection.HTTP_NOT_FOUND: inputStream = connection.getErrorStream(); break; case HttpsURLConnection.HTTP_UNAUTHORIZED: inputStream = connection.getErrorStream(); break; default: inputStream = connection.getInputStream(); break; } String responseContent = "{}"; // Default to an empty object. if (inputStream != null) { responseContent = readInputStream(inputStream, connection.getContentLength()); } JSONObject responseObject = new JSONObject(responseContent); responseObject.put("code", responseCode); return responseObject; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }