List of usage examples for javax.net.ssl HttpsURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.gmt2001.TwitchAPIv5.java
@SuppressWarnings("UseSpecificCatch") private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) { JSONObject j = new JSONObject("{}"); InputStream i = null;/*from ww w. ja v a 2 s .c o m*/ String content = ""; try { URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.addRequestProperty("Accept", header_accept); c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded"); if (!clientid.isEmpty()) { c.addRequestProperty("Client-ID", clientid); } if (!oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } else { if (!this.oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } } c.setRequestMethod(type.name()); c.setConnectTimeout(timeout); c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); if (!post.isEmpty()) { c.setDoOutput(true); } c.connect(); if (!post.isEmpty()) { try (OutputStream o = c.getOutputStream()) { IOUtils.write(post, o); } } if (c.getResponseCode() == 200) { i = c.getInputStream(); } else { i = c.getErrorStream(); } if (c.getResponseCode() == 204 || i == null) { content = "{}"; } else { // default to UTF-8, it'll probably be the best bet if there's // no charset specified. String charset = "utf-8"; String ct = c.getContentType(); if (ct != null) { String[] cts = ct.split(" *; *"); for (int idx = 1; idx < cts.length; ++idx) { String[] val = cts[idx].split("=", 2); if (val[0] == "charset" && val.length > 1) { charset = val[1]; } } } if ("gzip".equals(c.getContentEncoding())) { i = new GZIPInputStream(i); } content = IOUtils.toString(i, charset); } j = new JSONObject(content); fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content); } catch (Exception ex) { Throwable rootCause = ex; while (rootCause.getCause() != null && rootCause.getCause() != rootCause) { rootCause = rootCause.getCause(); } fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(), content); com.gmt2001.Console.debug .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage()); } finally { if (i != null) { try { i.close(); } catch (IOException ex) { fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content); com.gmt2001.Console.err.println("IOException: " + ex.getMessage()); } } } return j; }
From source file:com.citrus.mobile.RESTclient.java
public JSONObject makeSendMoneyRequest(String accessToken, CitrusUser toUser, Amount amount, String message) { HttpsURLConnection conn; DataOutputStream wr = null;/*from ww w. ja v a 2s. c o m*/ JSONObject txnDetails = null; BufferedReader in = null; try { String url = null; StringBuffer postDataBuff = new StringBuffer("amount="); postDataBuff.append(amount.getValue()); postDataBuff.append("¤cy="); postDataBuff.append(amount.getCurrency()); postDataBuff.append("&message="); postDataBuff.append(message); if (!TextUtils.isEmpty(toUser.getEmailId())) { url = urls.getString(base_url) + urls.getString("transfer"); postDataBuff.append("&to="); postDataBuff.append(toUser.getEmailId()); } else if (!TextUtils.isEmpty(toUser.getMobileNo())) { url = urls.getString(base_url) + urls.getString("suspensetransfer"); postDataBuff.append("&to="); postDataBuff.append(toUser.getMobileNo()); } conn = (HttpsURLConnection) new URL(url).openConnection(); //add reuqest header conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + accessToken); conn.setDoOutput(true); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(postDataBuff.toString()); wr.flush(); int responseCode = conn.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + postDataBuff.toString()); System.out.println("Response Code : " + responseCode); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } txnDetails = new JSONObject(response.toString()); } catch (JSONException exception) { exception.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } try { if (wr != null) { wr.close(); } } catch (IOException e) { e.printStackTrace(); } } return txnDetails; }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public HttpsURLConnection makeRequest(String verb, String url, @Nullable String postData, boolean json, boolean autoredirect, @Nullable Map<String, String> customHeaders) throws IOException, URISyntaxException { String currentUrl = url;/*from w w w. j a v a 2 s . co m*/ for (int i = 0; i < 30; i++) // loop for handling redirect, using automatic redirect is not possible, because // all response headers must be catched { int code; HttpsURLConnection connection = null; try { logger.debug("Make request to {}", url); connection = (HttpsURLConnection) new URL(currentUrl).openConnection(); connection.setRequestMethod(verb); connection.setRequestProperty("Accept-Language", "en-US"); if (customHeaders == null || !customHeaders.containsKey("User-Agent")) { connection.setRequestProperty("User-Agent", userAgent); } connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("DNT", "1"); connection.setRequestProperty("Upgrade-Insecure-Requests", "1"); if (customHeaders != null) { for (String key : customHeaders.keySet()) { String value = customHeaders.get(key); if (StringUtils.isNotEmpty(value)) { connection.setRequestProperty(key, value); } } } connection.setInstanceFollowRedirects(false); // add cookies URI uri = connection.getURL().toURI(); if (customHeaders == null || !customHeaders.containsKey("Cookie")) { StringBuilder cookieHeaderBuilder = new StringBuilder(); for (HttpCookie cookie : cookieManager.getCookieStore().get(uri)) { if (cookieHeaderBuilder.length() > 0) { cookieHeaderBuilder.append(";"); } cookieHeaderBuilder.append(cookie.getName()); cookieHeaderBuilder.append("="); cookieHeaderBuilder.append(cookie.getValue()); if (cookie.getName().equals("csrf")) { connection.setRequestProperty("csrf", cookie.getValue()); } } if (cookieHeaderBuilder.length() > 0) { String cookies = cookieHeaderBuilder.toString(); connection.setRequestProperty("Cookie", cookies); } } if (postData != null) { logger.debug("{}: {}", verb, postData); // post data byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8); int postDataLength = postDataBytes.length; connection.setFixedLengthStreamingMode(postDataLength); if (json) { connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); } else { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); if (verb == "POST") { connection.setRequestProperty("Expect", "100-continue"); } connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(postDataBytes); outputStream.close(); } // handle result code = connection.getResponseCode(); String location = null; // handle response headers Map<String, List<String>> headerFields = connection.getHeaderFields(); for (Map.Entry<String, List<String>> header : headerFields.entrySet()) { String key = header.getKey(); if (StringUtils.isNotEmpty(key)) { if (key.equalsIgnoreCase("Set-Cookie")) { // store cookie for (String cookieHeader : header.getValue()) { if (StringUtils.isNotEmpty(cookieHeader)) { List<HttpCookie> cookies = HttpCookie.parse(cookieHeader); for (HttpCookie cookie : cookies) { cookieManager.getCookieStore().add(uri, cookie); } } } } if (key.equalsIgnoreCase("Location")) { // get redirect location location = header.getValue().get(0); if (StringUtils.isNotEmpty(location)) { location = uri.resolve(location).toString(); // check for https if (location.toLowerCase().startsWith("http://")) { // always use https location = "https://" + location.substring(7); logger.debug("Redirect corrected to {}", location); } } } } } if (code == 200) { logger.debug("Call to {} succeeded", url); return connection; } if (code == 302 && location != null) { logger.debug("Redirected to {}", location); currentUrl = location; if (autoredirect) { continue; } return connection; } } catch (IOException e) { if (connection != null) { connection.disconnect(); } logger.warn("Request to url '{}' fails with unkown error", url, e); throw e; } catch (Exception e) { if (connection != null) { connection.disconnect(); } throw e; } if (code != 200) { throw new HttpException(code, verb + " url '" + url + "' failed: " + connection.getResponseMessage()); } } throw new ConnectionException("Too many redirects"); }
From source file:eu.faircode.netguard.ServiceJob.java
@Override public boolean onStartJob(JobParameters params) { Log.i(TAG, "Start job=" + params.getJobId()); new AsyncTask<JobParameters, Object, Object>() { @Override/* w ww . j a v a 2 s . c o m*/ protected JobParameters doInBackground(JobParameters... params) { Log.i(TAG, "Executing job=" + params[0].getJobId()); HttpsURLConnection urlConnection = null; try { String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); JSONObject json = new JSONObject(); json.put("device", Util.sha256(android_id, "")); json.put("product", Build.DEVICE); json.put("sdk", Build.VERSION.SDK_INT); json.put("country", Locale.getDefault().getCountry()); json.put("netguard", Util.getSelfVersionCode(ServiceJob.this)); try { json.put("store", getPackageManager().getInstallerPackageName(getPackageName())); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); json.put("store", null); } for (String name : params[0].getExtras().keySet()) json.put(name, params[0].getExtras().get(name)); urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection(); urlConnection.setConnectTimeout(cTimeOutMs); urlConnection.setReadTimeout(cTimeOutMs); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Content-type", "application/json"); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(json.toString().getBytes()); // UTF-8 out.flush(); int code = urlConnection.getResponseCode(); if (code != HttpsURLConnection.HTTP_OK) throw new IOException("HTTP " + code); InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream()); Log.i(TAG, "Response=" + Util.readString(isr).toString()); jobFinished(params[0], false); if ("rule".equals(params[0].getExtras().getString("type"))) { SharedPreferences history = getSharedPreferences("history", Context.MODE_PRIVATE); history.edit().putLong(params[0].getExtras().getString("package") + ":submitted", new Date().getTime()).apply(); } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); jobFinished(params[0], true); } finally { if (urlConnection != null) urlConnection.disconnect(); try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } return null; } }.execute(params); return true; }
From source file:org.kuali.mobility.push.dao.PushDaoImpl.java
@SuppressWarnings("unchecked") private boolean sendPushToAndroid(Push push, Device device) { try {/* www. j a v a 2s. c o 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: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();/*from w w w.jav a 2 s. co m*/ } 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 ww w . j av 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.globusonline.nexus.BaseNexusRestClient.java
/** * @param path/* w ww . j av a2s . 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.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();// ww w . j av a 2 s . c o m 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.csp.everyaware.internet.StoreAndForwardService.java
public int postSecureData() throws IllegalArgumentException, ClientProtocolException, HttpHostConnectException, IOException { Log.d("StoreAndForwardService", "postSecureData()"); //get size of array of records to send and reference to the last record int size = mToSendRecords.size(); if (size == 0) return -1; int sepIndex = 1; //default is '.' separator (see Constants.separators array) if ((Utils.report_country != null) && (Utils.report_country.equals("IT"))) sepIndex = 0; //0 is for '-' separator (for italian CSP server) Record lastToSendRecord = mToSendRecords.get(size - 1); Log.d("StoreAndForwardService", "postSecureData()--> # of records: " + size); //save timestamp long lastTimestamp = 0; if (lastToSendRecord.mSysTimestamp > 0) lastTimestamp = lastToSendRecord.mSysTimestamp; else/*ww w .j a v a 2 s . c o m*/ lastTimestamp = lastToSendRecord.mBoxTimestamp; String lastTsFormatted = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSSz", Locale.US) .format(new Date(lastTimestamp)); //********* MAKING OF HTTP HEADER ************** URL url = new URL(Utils.report_url); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setUseCaches(false); con.setDoInput(true); con.setDoOutput(true); con.setRequestProperty("Content-Encoding", "gzip"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("User-Agent", "AirProbe" + Utils.appVer); //******** authorization bearer header ******** //air probe can be used also anymously. If account activation state is true (--> AirProbe activated) add this header if (Utils.getAccountActivationState(getApplicationContext())) con.setRequestProperty("Authorization", "Bearer " + Utils.getAccessToken(getApplicationContext())); else if (Utils.getAccountActivationStateForClient(getApplicationContext())) con.setRequestProperty("Authorization", "Bearer " + Utils.getAccessTokenForClient(getApplicationContext())); //******** meta header (for new version API V1) con.setRequestProperty("meta" + Constants.separators[sepIndex] + "timestampRecorded", lastTsFormatted); //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"sessionId", lastToSendRecord.mSessionId); //deprecated from AP 1.4 con.setRequestProperty("meta" + Constants.separators[sepIndex] + "deviceId", Utils.deviceID); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "installId", Utils.installID); //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"userFeedId", ""); //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"eventFeedId", ""); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "visibilityEvent", Constants.DATA_VISIBILITY[0]); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "visibilityGlobal", Constants.DATA_VISIBILITY[0]); //set meta.visibilityGlobal=DETAILS for testing (to retrieve data after insertion) /* from AP 1.4 */ if ((lastToSendRecord.mBoxMac != null) && (!lastToSendRecord.mBoxMac.equals(""))) { Log.d("StoreAndForwardService", "postSecureData()--> box mac address: " + lastToSendRecord.mBoxMac); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId", lastToSendRecord.mBoxMac); } else con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId", Utils.getDeviceAddress(getApplicationContext())); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceSessionId" + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSourceSessionSeed); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceSessionId" + Constants.separators[sepIndex] + "number", String.valueOf(lastToSendRecord.mSourceSessionNumber)); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceSessionPointNumber", String.valueOf(lastToSendRecord.mSourcePointNumber)); if ((lastToSendRecord.mSemanticSessionSeed != null) && (!lastToSendRecord.mSemanticSessionSeed.equals(""))) { con.setRequestProperty("meta" + Constants.separators[sepIndex] + "semanticSessionId" + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSemanticSessionSeed); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "semanticSessionId" + Constants.separators[sepIndex] + "number", String.valueOf(lastToSendRecord.mSemanticSessionNumber)); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "semanticSessionPointNumber", String.valueOf(lastToSendRecord.mSemanticPointNumber)); } con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "typeVersion", "30"); //update by increment this field on header changes /* end of from AP 1.4 */ //******** data header (for new version API V1) con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "type", "airprobe_report"); con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "format", "json"); //con.setRequestProperty("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "a-3"); //deprecated from AP 1.4 if (size > 1) con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "list", "true"); else con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "list", "false"); con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "listSize", String.valueOf(size)); //******** geo header (for new version API V1) //add the right provider to header if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[0])) //sensor box { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mBoxLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mBoxLat)); if (lastToSendRecord.mBoxAcc != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "hdop", String.valueOf(lastToSendRecord.mBoxAcc)); //from AP 1.4 if (lastToSendRecord.mBoxAltitude != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude", String.valueOf(lastToSendRecord.mBoxAltitude)); //from AP 1.4 if (lastToSendRecord.mBoxSpeed != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed", String.valueOf(lastToSendRecord.mBoxSpeed)); //from AP 1.4 if (lastToSendRecord.mBoxBear != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing", String.valueOf(lastToSendRecord.mBoxBear)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mPhoneLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mPhoneLat)); if (lastToSendRecord.mPhoneAcc != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy", String.valueOf(lastToSendRecord.mPhoneAcc)); if (lastToSendRecord.mPhoneAltitude != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude", String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4 if (lastToSendRecord.mPhoneSpeed != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed", String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4 if (lastToSendRecord.mPhoneBear != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing", String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mNetworkLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mNetworkLat)); if (lastToSendRecord.mNetworkAcc != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy", String.valueOf(lastToSendRecord.mNetworkAcc)); if (lastToSendRecord.mNetworkAltitude != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude", String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4 if (lastToSendRecord.mNetworkSpeed != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed", String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4 if (lastToSendRecord.mNetworkBear != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing", String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } //******** MAKING OF HTTP CONTENT (JSON) ************* //writing string content as an array of json object StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < mToSendRecords.size(); i++) { sb.append(mToSendRecords.get(i).toJson().toString()); if ((size != 0) && (i != size - 1)) sb.append(","); sb.append("\n"); } sb.append("]"); //Log.d("StoreAndForwardService", "postSecureData()--> json: " +sb.toString()); //Log.d("StoreAndForwardService", "postSecureData()--> access token: "+Utils.getAccessToken(getApplicationContext())); //compress json content into byte array entity byte[] contentGzippedBytes = zipStringToBytes(sb.toString()); //write json compressed content into output stream OutputStream outputStream = con.getOutputStream(); outputStream.write(contentGzippedBytes); outputStream.flush(); outputStream.close(); int responseCode = con.getResponseCode(); Log.d("StoreAndForwardService", "postSecureData()--> response code: " + responseCode); sb = null; return responseCode; }