List of usage examples for javax.net.ssl HttpsURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.siviton.huanapi.data.HuanApi.java
public void AutoLoginUser() { new Thread() { public void run() { JSONObject jsonObject2 = new JSONObject(); try { jsonObject2.putOpt("dnum", getdnum()); jsonObject2.putOpt("didtoken", getdidtoken()); } catch (JSONException e2) { // TODO Auto-generated catch block e2.printStackTrace();// www .j av a2s . c om } JSONObject jsonObject = new JSONObject(); try { jsonObject.putOpt("action", "AutoLoginUser"); jsonObject.putOpt("device", jsonObject2); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { byte[] entity = jsonObject.toString().getBytes(); URL url = new URL(getDeviceUrl()); HttpsURLConnection connections = (HttpsURLConnection) url.openConnection(); if (connections instanceof HttpsURLConnection) { // Trust all certificates SSLContext context = SSLContext.getInstance("SSL"); context.init(new KeyManager[0], xtmArray, new SecureRandom()); SSLSocketFactory socketFactory = context.getSocketFactory(); ((HttpsURLConnection) connections).setSSLSocketFactory(socketFactory); ((HttpsURLConnection) connections).setHostnameVerifier(HOSTNAME_VERIFIER); } connections.setConnectTimeout(5 * 1000); connections.setRequestMethod("POST"); connections.setDoOutput(true);// ?? connections.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connections.setRequestProperty("Content-Length", String.valueOf(entity.length)); OutputStream outStream = connections.getOutputStream(); outStream.write(entity); outStream.flush(); outStream.close(); if (connections.getResponseCode() == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(connections.getInputStream())); String line = ""; StringBuilder stringBuffer = new StringBuilder(); while ((line = in.readLine()) != null) { stringBuffer.append("" + line + "\n"); System.out.println("==pengbdata==AutoLoginUser=====" + line); } in.close(); JSONObject object = new JSONObject("" + stringBuffer.toString()); JSONObject object2 = null; try { object2 = object.getJSONObject("error"); String code = object2.getString("code"); String info = object2.getString("info"); if (!code.equals("0")) { mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_ERROR_COCDE, "" + info, null, null, null); } else { object2 = object.getJSONObject("user"); String huanid = object2.getString("huanid"); String token = object2.getString("token"); if (token != null && huanid != null) { huanItemInfo.setToken(token); huanItemInfo.setHuanid(huanid); updateData(); mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_LOGIN_SUCC, "user succ", null, null, null); } else { // ? mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_HUANIDTOKEN_NULL, "huanid or huanid is null", null, null, null); } } } catch (Exception e) { // TODO: handle exception mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_JESON_EXCEPTION, e.toString(), null, null, null); } } else { // mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_NETCODE_ISNO200, "user network error", null, null, null); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_NETCODE_EXCEPTION, "user network error" + e.toString(), null, null, null); } }; }.start(); }
From source file:com.siviton.huanapi.data.HuanApi.java
public void DeviceLogin() { new Thread() { public void run() { JSONObject jsonObject2 = new JSONObject(); try { jsonObject2.putOpt("dnum", getdnum()); jsonObject2.putOpt("didtoken", getdidtoken()); jsonObject2.putOpt("activekey", getactivekey()); } catch (JSONException e2) { // TODO Auto-generated catch block e2.printStackTrace();/*from w w w . jav a 2 s . c o m*/ } JSONObject jsonObject3 = new JSONObject(); try { jsonObject3.putOpt("ostype", getostype()); jsonObject3.putOpt("osversion", getosversion()); jsonObject3.putOpt("kernelversion", getkernelversion()); jsonObject3.putOpt("webinfo", getwebinfo()); jsonObject3.putOpt("javainfo", getjavainfo()); jsonObject3.putOpt("flashinfo", getflashinfo()); } catch (JSONException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } JSONObject jsonObject = new JSONObject(); try { jsonObject.putOpt("action", "DeviceLogin"); jsonObject.putOpt("device", jsonObject2); jsonObject.putOpt("param", jsonObject3); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { byte[] entity = jsonObject.toString().getBytes(); URL url = new URL(getDeviceUrl()); HttpsURLConnection connections = (HttpsURLConnection) url.openConnection(); if (connections instanceof HttpsURLConnection) { // Trust all certificates SSLContext context = SSLContext.getInstance("SSL"); context.init(new KeyManager[0], xtmArray, new SecureRandom()); SSLSocketFactory socketFactory = context.getSocketFactory(); ((HttpsURLConnection) connections).setSSLSocketFactory(socketFactory); ((HttpsURLConnection) connections).setHostnameVerifier(HOSTNAME_VERIFIER); } connections.setConnectTimeout(5 * 1000); connections.setRequestMethod("POST"); connections.setDoOutput(true);// ?? connections.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connections.setRequestProperty("Content-Length", String.valueOf(entity.length)); OutputStream outStream = connections.getOutputStream(); outStream.write(entity); outStream.flush(); outStream.close(); if (connections.getResponseCode() == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(connections.getInputStream())); String line = ""; StringBuilder stringBuffer = new StringBuilder(); while ((line = in.readLine()) != null) { stringBuffer.append("" + line + "\n"); System.out.println("==pengbdata==DeviceLogin=====" + line); } in.close(); JSONObject object = new JSONObject("" + stringBuffer.toString()); JSONObject object2 = null; try { object2 = object.getJSONObject("error"); String code = object2.getString("code"); String info = object2.getString("info"); if (!code.equals("0")) { mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_ERROR_COCDE, "" + info, null, null, null); } else { object2 = object.getJSONObject("device"); String activekey = object2.getString("activekey"); if (activekey != null) { huanItemInfo.setActivekey(activekey); huanItemInfo.setDidtoken(getMD5(getdeviceid() + getactivekey())); System.out.println("==pengbdata==DeviceLogin======" + huanItemInfo.getDeviceid() + "===" + huanItemInfo.getDevicemodel() + "===" + huanItemInfo.getDidtoken() + "===" + huanItemInfo.getActivekey() + "===" + huanItemInfo.getDnum()); updateData(); mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_LOGIN_SUCC, "DeviceLogin succ", null, null, null); } else { // ? mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_ACTIVEKEY_NULL, "dnum or activekey is null", null, null, null); } } } catch (Exception e) { // TODO: handle exception mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_JESON_EXCEPTION, e.toString(), null, null, null); } } else { // mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_NETCODE_ISNO200, "DeviceLogin network error", null, null, null); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_NETCODE_EXCEPTION, "DeviceLogin network error" + e.toString(), null, null, null); } }; }.start(); }
From source file:org.kuali.mobility.push.dao.PushDaoImpl.java
@SuppressWarnings("unchecked") private boolean sendPushToAndroid(Push push, Device device) { try {/*from w ww .jav a2 s .co m*/ HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier()); URL url = new URL("https://android.apis.google.com/c2dm/send"); HttpsURLConnection request = (HttpsURLConnection) url.openConnection(); LOG.info("---- Version: " + url.getClass().getPackage().getSpecificationVersion()); LOG.info("---- Impl: " + url.getClass().getPackage().getImplementationVersion()); String handlers = System.getProperty("java.protocol.handler.pkgs"); LOG.info(handlers); request.setDoOutput(true); request.setDoInput(true); StringBuilder buf = new StringBuilder(); buf.append("registration_id").append("=").append((URLEncoder.encode(device.getRegId(), "UTF-8"))); buf.append("&collapse_key").append("=") .append((URLEncoder.encode(push.getPostedTimestamp().toString(), "UTF-8"))); buf.append("&data.message").append("=").append((URLEncoder.encode(push.getMessage(), "UTF-8"))); buf.append("&data.title").append("=").append((URLEncoder.encode(push.getTitle(), "UTF-8"))); buf.append("&data.id").append("=").append((URLEncoder.encode(push.getPushId().toString(), "UTF-8"))); buf.append("&data.url").append("=").append((URLEncoder.encode(push.getUrl().toString(), "UTF-8"))); String emer = (push.getEmergency()) ? "YES" : "NO"; buf.append("&data.emer").append("=").append((URLEncoder.encode(emer, "UTF-8"))); request.setRequestMethod("POST"); request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); request.setRequestProperty("Content-Length", buf.toString().getBytes().length + ""); request.setRequestProperty("Authorization", "GoogleLogin auth=" + GoogleAuthToken); LOG.info("SEND Android Buffer: " + buf.toString()); OutputStreamWriter post = new OutputStreamWriter(request.getOutputStream()); post.write(buf.toString()); post.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream())); buf = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } post.close(); in.close(); LOG.info("response from C2DM server:\n" + buf.toString()); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; }
From source file:org.globusonline.nexus.BaseNexusRestClient.java
/** * @param path//from w w w . j a v a2 s .co m * @return JSON Response from action * @throws NexusClientException */ protected JSONObject issueRestRequest(String path, String httpMethod, String contentType, String accept, JSONObject params, NexusAuthenticator auth) throws NexusClientException { JSONObject json = null; HttpsURLConnection connection; if (httpMethod.isEmpty()) { httpMethod = "GET"; } if (contentType.isEmpty()) { contentType = "application/json"; } if (accept.isEmpty()) { accept = "application/json"; } int responseCode; try { URL url = new URL(getNexusApiUrl() + path); connection = (HttpsURLConnection) url.openConnection(); if (ignoreCertErrors) { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); connection.setSSLSocketFactory(sc.getSocketFactory()); connection.setHostnameVerifier(allHostsValid); } if (auth != null) { auth.authenticate(connection); } connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(httpMethod); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Accept", accept); connection.setRequestProperty("X-Go-Community-Context", community); String body = ""; if (params != null) { OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); body = params.toString(); out.write(body); logger.debug("Body:" + body); out.close(); } responseCode = connection.getResponseCode(); } catch (Exception e) { logger.error("Unhandled connection error:", e); throw new ValueErrorException(); } logger.info("ConnectionURL: " + connection.getURL()); if (responseCode == 403 || responseCode == 400) { logger.error("Access is denied. Invalid credentials."); throw new InvalidCredentialsException(); } if (responseCode == 404) { logger.error("URL not found."); throw new InvalidUrlException(); } if (responseCode == 500) { logger.error("Internal Server Error."); throw new ValueErrorException(); } if (responseCode != 200) { logger.info("Response code is: " + responseCode); } try { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString = in.readLine(); json = new JSONObject(decodedString); } catch (JSONException e) { logger.error("JSON Error", e); throw new ValueErrorException(); } catch (IOException e) { logger.error("IO Error", e); throw new ValueErrorException(); } return json; }
From source file:com.echopf.ECHOQuery.java
/** * Sends a HTTP request with optional request contents/parameters. * @param path a request url path/*from www. j av a 2 s . c o m*/ * @param httpMethod a request method (GET/POST/PUT/DELETE) * @param data request contents/parameters * @param multipart use multipart/form-data to encode the contents * @throws ECHOException */ public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart) throws ECHOException { final String secureDomain = ECHO.secureDomain; if (secureDomain == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); String baseUrl = new StringBuilder("https://").append(secureDomain).toString(); String url = new StringBuilder(baseUrl).append("/").append(path).toString(); HttpsURLConnection httpClient = null; try { URL urlObj = new URL(url); StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/"); // Append the QueryString contained in path boolean isContainQuery = urlObj.getQuery() != null; if (isContainQuery) apiUrl.append("?").append(urlObj.getQuery()); // Append the QueryString from data if (httpMethod.equals("GET") && data != null) { boolean firstItem = true; Iterator<?> iter = data.keys(); while (iter.hasNext()) { if (firstItem && !isContainQuery) { firstItem = false; apiUrl.append("?"); } else { apiUrl.append("&"); } String key = (String) iter.next(); String value = data.optString(key); apiUrl.append(key); apiUrl.append("="); apiUrl.append(value); } } URL urlConn = new URL(apiUrl.toString()); httpClient = (HttpsURLConnection) urlConn.openConnection(); } catch (IOException e) { throw new ECHOException(e); } final String appId = ECHO.appId; final String appKey = ECHO.appKey; final String accessToken = ECHO.accessToken; if (appId == null || appKey == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); InputStream responseInputStream = null; try { httpClient.setRequestMethod(httpMethod); httpClient.addRequestProperty("X-ECHO-APP-ID", appId); httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey); // Set access token if (accessToken != null && !accessToken.isEmpty()) httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken); // Build content if (!httpMethod.equals("GET") && data != null) { httpClient.setDoOutput(true); httpClient.setChunkedStreamingMode(0); // use default chunk size if (multipart == false) { // application/json httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); BufferedWriter wrBuffer = new BufferedWriter( new OutputStreamWriter(httpClient.getOutputStream())); wrBuffer.write(data.toString()); wrBuffer.close(); } else { // multipart/form-data final String boundary = "*****" + UUID.randomUUID().toString() + "*****"; final String twoHyphens = "--"; final String lineEnd = "\r\n"; final int maxBufferSize = 1024 * 1024 * 3; httpClient.setRequestMethod("POST"); httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary); final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream()); try { JSONObject postData = new JSONObject(); postData.putOpt("method", httpMethod); postData.putOpt("data", data); new Object() { public void post(JSONObject data, List<String> currentKeys) throws JSONException, IOException { Iterator<?> keys = data.keys(); while (keys.hasNext()) { String key = (String) keys.next(); List<String> newKeys = new ArrayList<String>(currentKeys); newKeys.add(key); Object val = data.get(key); // convert JSONArray into JSONObject if (val instanceof JSONArray) { JSONArray array = (JSONArray) val; JSONObject val2 = new JSONObject(); for (Integer i = 0; i < array.length(); i++) { val2.putOpt(i.toString(), array.get(i)); } val = val2; } // build form-data name String name = ""; for (int i = 0; i < newKeys.size(); i++) { String key2 = newKeys.get(i); name += (i == 0) ? key2 : "[" + key2 + "]"; } if (val instanceof ECHOFile) { ECHOFile file = (ECHOFile) val; if (file.getLocalBytes() == null) continue; InputStream fileInputStream = new ByteArrayInputStream( file.getLocalBytes()); if (fileInputStream != null) { String mimeType = URLConnection .guessContentTypeFromName(file.getFileName()); // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + mimeType + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); // write content int bytesAvailable, bufferSize, bytesRead; do { bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (bytesRead <= 0) break; outputStream.write(buffer, 0, bufferSize); } while (true); fileInputStream.close(); outputStream.writeBytes(lineEnd); } } else if (val instanceof JSONObject) { this.post((JSONObject) val, newKeys); } else { String data2 = null; try { // in case of boolean boolean bool = data.getBoolean(key); data2 = bool ? "true" : ""; } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false". data2 = val.toString().trim(); } // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes( "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd); outputStream .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd); outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd); outputStream.writeBytes(lineEnd); // write content byte[] bytes = data2.getBytes(); for (int i = 0; i < bytes.length; i++) { outputStream.writeByte(bytes[i]); } outputStream.writeBytes(lineEnd); } } } }.post(postData, new ArrayList<String>()); } catch (JSONException e) { throw new ECHOException(e); } finally { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.flush(); outputStream.close(); } } } else { httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); } if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) { responseInputStream = httpClient.getInputStream(); } } catch (IOException e) { // get http response code int errorCode = -1; try { errorCode = httpClient.getResponseCode(); } catch (IOException e1) { throw new ECHOException(e1); } // get error contents JSONObject responseObj; try { String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream()); responseObj = new JSONObject(jsonStr); } catch (JSONException e1) { if (errorCode == 404) { throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found."); } throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format."); } // if (responseObj != null) { int code = responseObj.optInt("error_code"); String message = responseObj.optString("error_message"); if (code != 0 || !message.equals("")) { JSONObject details = responseObj.optJSONObject("error_details"); if (details == null) { throw new ECHOException(code, message); } else { throw new ECHOException(code, message, details); } } } throw new ECHOException(e); } return responseInputStream; }
From source file:com.example.android.networkconnect.MainActivity.java
private String https_test(String urlString) throws IOException { String token = ""; URL url = new URL(urlString); Log.i(TAG, "Protocol: " + url.getProtocol().toString()); // if (url.getProtocol().toLowerCase().equals("https")) { trustAllHosts();/* ww w . j ava 2 s . c o m*/ HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(20000 /* milliseconds */); conn.setConnectTimeout(25000 /* milliseconds */); // conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.setRequestProperty("User-Agent", "e-venement-app/"); // OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); //writer.getEncoding(); //writer.write("&signin[username]=antoine"); //writer.write("&signin[password]=android2015@"); //writer.write("?control[id]="); //writer.write("&control[ticket_id]=2222"); //writer.write("&control[checkpoint_id]=1"); // writer.write("&control[comment]="); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //On cre la liste qui contiendra tous nos paramtres //Et on y rajoute nos paramtres nameValuePairs.add(new BasicNameValuePair("signin[username]", "antoine")); nameValuePairs.add(new BasicNameValuePair("signin[password]", "android2015@")); //nameValuePairs.add(new BasicNameValuePair("control[id]", "")); //nameValuePairs.add(new BasicNameValuePair("control[ticket_id]", "2222")); //nameValuePairs.add(new BasicNameValuePair("control[checkpoint_id]", "1")); //nameValuePairs.add(new BasicNameValuePair("control[comment]", "")); OutputStream os = conn.getOutputStream(); BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer2.write(getQuery(nameValuePairs)); writer2.flush(); //writer2.close(); //os.close(); // conn.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //writer.write("&signin[_csrf_token]="+CSRFTOKEN); //writer.flush(); conn.connect(); String headerName = null; for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) { //data=data+"Header Nme : " + headerName; //data=data+conn.getHeaderField(i); // Log.i (TAG,headerName); Log.i(TAG, headerName + ": " + conn.getHeaderField(i)); } int responseCode = conn.getResponseCode(); if (responseCode == conn.HTTP_OK) { final String COOKIES_HEADER = "Set-Cookie"; cookie = conn.getHeaderField(COOKIES_HEADER); } if (conn.getInputStream() != null) { // token =getStringFromInputStream(conn.getInputStream()); Log.i(TAG, readIt(conn.getInputStream(), 15000)); token = readIt(conn.getInputStream(), 15000); Log.i(TAG, getStringFromInputStream(conn.getInputStream())); //data=readIt(conn.getInputStream(),7500); //Log.i(TAG,token); //token=readIt(conn.getInputStream(),7500); } //conn.connect(); // List<String> cookiesList = conn.getHeaderFields().get("Set-Cookie"); // } //conn.disconnect(); return token; }
From source file:TestHTTPSource.java
public void doTestHttps(String protocol) throws Exception { Type listType = new TypeToken<List<JSONEvent>>() { }.getType();// w w w .j a v a 2 s. c o m List<JSONEvent> events = Lists.newArrayList(); Random rand = new Random(); for (int i = 0; i < 10; i++) { Map<String, String> input = Maps.newHashMap(); for (int j = 0; j < 10; j++) { input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i)); } input.put("MsgNum", String.valueOf(i)); JSONEvent e = new JSONEvent(); e.setHeaders(input); e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8")); events.add(e); } Gson gson = new Gson(); String json = gson.toJson(events, listType); HttpsURLConnection httpsURLConnection = null; try { TrustManager[] trustAllCerts = { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // noop } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // noop } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sc = null; javax.net.ssl.SSLSocketFactory factory = null; if (System.getProperty("java.vendor").contains("IBM")) { sc = SSLContext.getInstance("SSL_TLS"); } else { sc = SSLContext.getInstance("SSL"); } HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }; sc.init(null, trustAllCerts, new SecureRandom()); if (protocol != null) { factory = new DisabledProtocolsSocketFactory(sc.getSocketFactory(), protocol); } else { factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(factory); HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); URL sslUrl = new URL("https://0.0.0.0:" + sslPort); httpsURLConnection = (HttpsURLConnection) sslUrl.openConnection(); httpsURLConnection.setDoInput(true); httpsURLConnection.setDoOutput(true); httpsURLConnection.setRequestMethod("POST"); httpsURLConnection.getOutputStream().write(json.getBytes()); int statusCode = httpsURLConnection.getResponseCode(); Assert.assertEquals(200, statusCode); Transaction transaction = channel.getTransaction(); transaction.begin(); for (int i = 0; i < 10; i++) { Event e = channel.take(); Assert.assertNotNull(e); Assert.assertEquals(String.valueOf(i), e.getHeaders().get("MsgNum")); } transaction.commit(); transaction.close(); } finally { httpsURLConnection.disconnect(); } }
From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java
private void sendHttpMessage() { if (mIsBitmap) { Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url); if (bitmap != null) { events.onHttpComplete(bitmap); return; }/*from www. j a va 2 s .c o m*/ } X509TrustManager trustManager = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE : This is where we can calculate the certificate's fingerprint, // show it to the user and throw an exception in case he doesn't like it } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }; //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier()); // Create a trust manager that does not validate certificate chains X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager }; // Install the all-trusting trust manager SSLSocketFactory noSSLv3Factory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom()); } else { noSSLv3Factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory); } catch (GeneralSecurityException e) { } HttpsURLConnection connection = null; try { URL urlObj = new URL(url); connection = (HttpsURLConnection) urlObj.openConnection(); connection.setSSLSocketFactory(noSSLv3Factory); HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost())); connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost())); byte[] postData = new byte[0]; if (message != null) { postData = message.getBytes("UTF-8"); } if (msCookieManager.getCookieStore().getCookies().size() > 0) { // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';' connection.setRequestProperty("Cookie", TextUtils.join(";", msCookieManager.getCookieStore().getCookies())); } /*if (method.equals("PATCH")) { connection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); connection.setRequestMethod("POST"); } else {*/ connection.setRequestMethod(method); //} if (authorization.length() != 0) { connection.setRequestProperty("Authorization", authorization); } connection.setUseCaches(false); connection.setDoInput(true); connection.setConnectTimeout(HTTP_TIMEOUT_MS); connection.setReadTimeout(HTTP_TIMEOUT_MS); // TODO(glaznev) - query request origin from pref_room_server_url_key preferences. //connection.addRequestProperty("origin", HTTP_ORIGIN); boolean doOutput = false; if (method.equals("POST") || method.equals("PATCH")) { doOutput = true; connection.setDoOutput(true); connection.setFixedLengthStreamingMode(postData.length); } if (contentType == null) { connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); } else { connection.setRequestProperty("Content-Type", contentType); } // Send POST request. if (doOutput && postData.length > 0) { OutputStream outStream = connection.getOutputStream(); outStream.write(postData); outStream.close(); } // Get response. int responseCode = 200; try { connection.getResponseCode(); } catch (IOException e) { } getCookies(connection); InputStream responseStream; if (responseCode > 400) { responseStream = connection.getErrorStream(); } else { responseStream = connection.getInputStream(); } String responseType = connection.getContentType(); if (responseType.startsWith("image/")) { Bitmap bitmap = BitmapFactory.decodeStream(responseStream); if (mIsBitmap && bitmap != null) { ThumbnailsCacheManager.addBitmapToCache(url, bitmap); } events.onHttpComplete(bitmap); } else { String response = drainStream(responseStream); events.onHttpComplete(response); } responseStream.close(); connection.disconnect(); } catch (SocketTimeoutException e) { events.onHttpError("HTTP " + method + " to " + url + " timeout"); } catch (IOException e) { if (connection != null) { connection.disconnect(); } events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage()); } catch (ClassCastException e) { e.printStackTrace(); } }
From source file:com.example.android.networkconnect.MainActivity.java
private String httpstestconnect(String urlString) throws IOException { CookieManager msCookieManager = new CookieManager(); URL url = new URL(urlString); if (url.getProtocol().toLowerCase().equals("https")) { trustAllHosts();//from ww w . j av a 2 s. c om HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); try { String headerName = null; for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) { //data=data+"Header Nme : " + headerName; //data=data+conn.getHeaderField(i); // Log.i (TAG,headerName); Log.i(TAG, headerName + ": " + conn.getHeaderField(i)); } // Map<String, List<String>> headerFields = conn.getHeaderFields(); //List<String> cookiesHeader = headerFields.get("Set-Cookie"); //if(cookiesHeader != null) //{ // for (String cookie : cookiesHeader) // { // msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0)); //} //} } catch (Exception e) { Log.i(TAG, "Erreur Cookie" + e); } conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.setRequestProperty("User-Agent", "e-venement-app/"); //if(msCookieManager.getCookieStore().getCookies().size() > 0) //{ // conn.setRequestProperty("Cookie", // TextUtils.join(",", msCookieManager.getCookieStore().getCookies())); //} // conn= (HttpsURLConnection) url.wait(); ; //(HttpsURLConnection) url.openConnection(); final String password = "android2015@"; OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.getEncoding(); writer.write("&signin[username]=antoine"); writer.write("&signin[password]=android2015@"); //writer.write("&signin[_csrf_token]="+CSRFTOKEN); writer.flush(); //Log.i(TAG,"Writer: "+writer.toString()); // conn.connect(); String data = null; // if (conn.getInputStream() != null) { Log.i(TAG, readIt(conn.getInputStream(), 2500)); data = readIt(conn.getInputStream(), 7500); } // return conn.getResponseCode(); return data; //return readIt(inputStream,1028); } else { return url.getProtocol(); } }
From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java
/** * Write REST request to {@link HttpsURLConnection}. * /* www.ja va 2s . c o m*/ * @param endPoint String End point URL. * @param httpMethod String HTTP method type (GET, POST, PUT etc.) * @param headersMap Map<String, String> Headers need to send to the end point. * @param requestFileName String File name of the file which contains request body data. * @param parametersMap Map<String, String> Additional parameters which is not predefined in the * properties file. * @return {@link HttpsURLConnection} object. * @throws IOException @ */ private HttpsURLConnection writeRequestHTTPS(String endPoint, String httpMethod, byte responseType, Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap, boolean isIgnoreHostVerification) throws IOException { String requestData = ""; if (requestFileName != null && !requestFileName.isEmpty()) { requestData = loadRequestFromFile(requestFileName, parametersMap); } else if (responseType == RestResponse.JSON_TYPE) { requestData = "{}"; } OutputStream output = null; URL url = new URL(endPoint); HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); // Disable automatic redirects httpsConnection.setInstanceFollowRedirects(false); httpsConnection.setRequestMethod(httpMethod); if (isIgnoreHostVerification) { httpsConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); } for (String key : headersMap.keySet()) { httpsConnection.setRequestProperty(key, headersMap.get(key)); } if (httpMethod.equalsIgnoreCase("POST") || httpMethod.equalsIgnoreCase("PUT")) { httpsConnection.setDoOutput(true); try { output = httpsConnection.getOutputStream(); output.write(requestData.getBytes(Charset.defaultCharset())); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } } return httpsConnection; }