List of usage examples for javax.net.ssl HttpsURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:mediasearch.twitter.TwitterService.java
public boolean writeRequest(HttpsURLConnection connection, String textBody) { try (BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()))) { wr.write(textBody);/*from w ww .ja v a2 s .c om*/ wr.flush(); } catch (IOException e) { return false; } return true; }
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);//w w w. ja v a 2s . 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:it.bz.tis.integreen.carsharingbzit.api.ApiClient.java
public <T> T callWebService(ServiceRequest request, Class<T> clazz) throws IOException { request.request.technicalUser.username = this.user; request.request.technicalUser.password = this.password; ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE) .setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY) .setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY) .setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, request);/*from ww w. j a va2 s . co m*/ String requestJson = sw.getBuffer().toString(); logger.debug("callWebService(): jsonRequest:" + requestJson); URL url = new URL(this.endpoint); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStream out = conn.getOutputStream(); out.write(requestJson.getBytes("UTF-8")); out.flush(); int responseCode = conn.getResponseCode(); InputStream input = conn.getInputStream(); ByteArrayOutputStream data = new ByteArrayOutputStream(); int len; byte[] buf = new byte[50000]; while ((len = input.read(buf)) > 0) { data.write(buf, 0, len); } conn.disconnect(); String jsonResponse = new String(data.toByteArray(), "UTF-8"); if (responseCode != 200) { throw new IOException(jsonResponse); } logger.debug("callWebService(): jsonResponse:" + jsonResponse); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); T response = mapper.readValue(new StringReader(jsonResponse), clazz); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); sw = new StringWriter(); mapper.writeValue(sw, response); logger.debug( "callWebService(): parsed response into " + response.getClass().getName() + ":" + sw.toString()); return response; }
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 ww . j a va 2 s . c om*/ 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:com.longtime.ajy.support.weixin.HttpsKit.java
/** * ??Post/* w ww . j a va 2 s.c o m*/ * * @param url * @param params * @return * @throws IOException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { OutputStream out = null; 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("POST"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); out = http.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); 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 POST url=[%s] param=[%s] due to fail.", url, params), e); } finally { if (null != out) { try { out.close(); } catch (IOException e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] close outputstream due to fail.", url, params), e); } } if (null != in) { try { in.close(); } catch (IOException e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url, params), e); } } if (http != null) { // http.disconnect(); } } return StringUtils.EMPTY; }
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 w ww .ja va2s. c om 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:net.portalblockz.portalbot.urlshorteners.GooGl.java
@Override public String shorten(String url) { StringBuilder response = new StringBuilder(); try {/*ww w . j a v a2 s. co m*/ URL req = new URL("https://www.googleapis.com/urlshortener/v1/url"); HttpsURLConnection con = (HttpsURLConnection) req.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes("{\"longUrl\": \"" + url + "\"}"); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject res = new JSONObject(response.toString()); if (res.optString("id") != null) return res.getString("id"); } catch (Exception ignored) { ignored.printStackTrace(); System.out.print(response.toString()); } return null; }
From source file:no.digipost.android.api.ApiAccess.java
public static void uploadFile(Context context, String uri, File file) throws DigipostClientException { try {//www. j a va 2s.com try { FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(ApiConstants.ENCODING)); multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()), ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING))); multipartEntity.addPart("file", filebody); multipartEntity.addPart("token", new StringBody(TokenStore.getAccess())); URL url = new URL(uri); HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection(); httpsClient.setRequestMethod("POST"); httpsClient.setDoOutput(true); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength()); } else { httpsClient.setChunkedStreamingMode(0); } httpsClient.setRequestProperty("Connection", "Keep-Alive"); httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + ""); httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION, ApiConstants.BEARER + TokenStore.getAccess()); httpsClient.addRequestProperty(multipartEntity.getContentType().getName(), multipartEntity.getContentType().getValue()); try { OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream()); multipartEntity.writeTo(outputStream); outputStream.flush(); NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode()); } finally { httpsClient.disconnect(); } } catch (DigipostInvalidTokenException e) { OAuth.updateAccessTokenWithRefreshToken(context); uploadFile(context, uri, file); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, context.getString(R.string.error_your_network)); throw new DigipostClientException(context.getString(R.string.error_your_network)); } }
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);// w w w .j av a2s .c o m 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.transitime.custom.missionBay.SfmtaApiCaller.java
/** * Posts the JSON string to the URL. For either the telemetry or the stop * command./*from ww w. jav a 2 s. c om*/ * * @param baseUrl * @param jsonStr * @return True if successfully posted the data */ private static boolean post(String baseUrl, String jsonStr) { try { // Create the connection URL url = new URL(baseUrl); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); // Set parameters for the connection con.setRequestMethod("POST"); con.setRequestProperty("content-type", "application/json"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); // API now uses basic authentication String authString = login.getValue() + ":" + password.getValue(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); con.setRequestProperty("Authorization", "Basic " + authStringEnc); // Set the timeout so don't wait forever (unless timeout is set to 0) int timeoutMsec = timeout.getValue(); con.setConnectTimeout(timeoutMsec); con.setReadTimeout(timeoutMsec); // Write the json data to the connection DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(jsonStr); wr.flush(); wr.close(); // Get the response int responseCode = con.getResponseCode(); // If wasn't successful then log the response so can debug if (responseCode != 200) { String responseStr = ""; if (responseCode != 500) { // Response code indicates there was a problem so get the // reply in case API returned useful error message InputStream inputStream = con.getErrorStream(); if (inputStream != null) { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); responseStr = response.toString(); } } // Lot that response code indicates there was a problem logger.error( "Bad HTTP response {} when writing data to SFMTA " + "API. Response text=\"{}\" URL={} json=\n{}", responseCode, responseStr, baseUrl, jsonStr); } // Done so disconnect just for the heck of it con.disconnect(); // Return whether was successful return responseCode == 200; } catch (IOException e) { logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(), baseUrl, jsonStr); // Return that was unsuccessful return false; } }