List of usage examples for javax.net.ssl HttpsURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public String requestASToken(Registration registration, String[] adds) throws IOException { String asToken = null;/*from w w w .ja v a 2 s . c om*/ // Token Acquisition // Create a HTTP request as in the following prototype and send // it via TLS to the AM // // Token Acquisition // Create a HTTP request as in the following prototype and send // it via TLS to the AM // Request // POST /iam-services/0.1/oidc/am/token HTTP/1.1 URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION); HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection(); httpConTokenAcquisition.setDoOutput(true); httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConTokenAcquisition.setRequestProperty("Accept", "application/json"); // httpConTokenAcquisition.setRequestProperty("Authorization", // "Basic Base64(<c_id>:<c_secret>"); String auth = registration.c_id + ":" + registration.c_secret; String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes())); httpConTokenAcquisition.setRequestProperty("Authorization", authb); httpConTokenAcquisition.setRequestMethod("POST"); String requestBodyTokenAcquisition = "grant_type=client_credentials"; if (adds == null || adds.length == 0) { // no additions } else { if (adds.length % 2 == 0) { for (int i = 0; i < (adds.length - 1); i += 2) { requestBodyTokenAcquisition += "&"; requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8"); requestBodyTokenAcquisition += "="; requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8"); } } else { log.warn( "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds)); } } OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream(); outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes()); outTokenAcquisition.close(); int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode(); log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": " + responseCodeoutTokenAcquisition); if (responseCodeoutTokenAcquisition == 200) { // everything ok InputStream isTA = httpConTokenAcquisition.getInputStream(); byte[] bisTA = getBytesFromInputStream(isTA); String jsonResponseTA = new String(bisTA); log.info(jsonResponseTA); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisTA); JsonNode actualObj = mapper.readTree(jp); JsonNode access_token = actualObj.get("access_token"); if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) { log.error("access_token: " + access_token); } else { // ok so far // access_token provides a JWT structure // see Understanding JWT // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html log.info("access_token: " + access_token); // http://jwt.io/ // TODO verify signature (e.g., use Jose4J) // Note: currently we assume signature is fine.. we just fetch // "as_token" String[] decAT = access_token.textValue().split("\\."); if (decAT == null || decAT.length != 3) { log.error("Cannot build JWT tripple structure for " + access_token); } else { assert (decAT.length == 3); // JWT structure // decAT[0]; // header // decAT[1]; // payload // decAT[2]; // signature String decAT1 = new String(Base64.getDecoder().decode(decAT[1])); JsonParser jpas = factory.createParser(decAT1); JsonNode payload = mapper.readTree(jpas); JsonNode as_token = payload.get("as_token"); if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) { log.error("as_token: " + as_token); } else { log.info("as_token: " + as_token); asToken = as_token.textValue(); } } } } else { // error InputStream error = httpConTokenAcquisition.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConTokenAcquisition.disconnect(); return asToken; }
From source file:se.leap.bitmaskclient.ProviderAPI.java
private boolean logOut() { String delete_url = provider_api_url + "/logout"; HttpsURLConnection urlConnection = null; int responseCode = 0; int progress = 0; try {/*ww w. j a va 2 s . c o m*/ urlConnection = (HttpsURLConnection) new URL(delete_url).openConnection(); urlConnection.setRequestMethod("DELETE"); urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory()); responseCode = urlConnection.getResponseCode(); broadcastProgress(progress++); LeapSRPSession.setToken(""); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IndexOutOfBoundsException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block try { if (urlConnection != null) { responseCode = urlConnection.getResponseCode(); if (responseCode == 401) { broadcastProgress(progress++); LeapSRPSession.setToken(""); return true; } } } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); return false; } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }
From source file:com.gmt2001.TwitchAPIv3.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 .j a v a 2 s.co m String rawcontent = ""; try { if (url.contains("?")) { url += "&utcnow=" + System.currentTimeMillis(); } else { url += "?utcnow=" + System.currentTimeMillis(); } URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.addRequestProperty("Accept", header_accept); if (isJson) { c.addRequestProperty("Content-Type", "application/json"); } else { c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } if (!clientid.isEmpty()) { c.addRequestProperty("Client-ID", clientid); } if (!oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); 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); } } String content; if (c.getResponseCode() == 200) { i = c.getInputStream(); } else { i = c.getErrorStream(); } if (c.getResponseCode() == 204 || i == null) { content = "{}"; } else { content = IOUtils.toString(i, c.getContentEncoding()); } rawcontent = content; j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_exception", ""); j.put("_exceptionMessage", ""); j.put("_content", content); } catch (JSONException ex) { if (ex.getMessage().contains("A JSONObject text must begin with")) { j = new JSONObject("{}"); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", ""); j.put("_exceptionMessage", ""); j.put("_content", rawcontent); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); com.gmt2001.Console.err.logStackTrace(ex); } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); com.gmt2001.Console.err.logStackTrace(ex); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); com.gmt2001.Console.err.logStackTrace(ex); } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); com.gmt2001.Console.err.logStackTrace(ex); } if (i != null) { try { i.close(); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); com.gmt2001.Console.err.logStackTrace(ex); } } return j; }
From source file:com.mb.ext.web.controller.UserController.java
@RequestMapping(value = "/getAirQuality", method = RequestMethod.GET) @ResponseStatus(HttpStatus.CREATED)/*w w w . j ava 2s . c o m*/ @ResponseBody public ResultDTO getAirQuality() { // AirQualityDTO airQualityDTO = new AirQualityDTO(); ResultDTO resultDTO = new ResultDTO(); String result = null; try { String httpUrl = Constants.WEATHER_URL; BufferedReader reader = null; InputStream is = null; StringBuffer sbf = new StringBuffer(); try { URL url = new URL(httpUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); is = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String strRead = null; while ((strRead = reader.readLine()) != null) { sbf.append(strRead); sbf.append("\r\n"); } result = sbf.toString(); } catch (Exception e) { e.printStackTrace(); } finally { reader.close(); is.close(); } resultDTO.setCode("0"); resultDTO.setMessage("Get air quality successfully"); } catch (Exception e) { resultDTO.setCode("1"); resultDTO.setMessage(e.getMessage()); } resultDTO.setBody(result); return resultDTO; }
From source file:com.mb.ext.web.controller.UserController.java
/** * //w ww.j av a2 s . c om * get news * */ @RequestMapping(value = "/pay", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public ResultDTO pay(@RequestBody PayDTO payDTO, HttpServletRequest request) { ResultDTO resultDTO = new ResultDTO(); PayRequest payRequest = new PayRequest(); payRequest.setAppid(WechatConstants.APPID_VALUE); payRequest.setMch_id(WechatConstants.MERCHANT_ID); payRequest.setNonce_str(RandomStringUtils.randomAlphanumeric(32)); payRequest.setOut_trade_no(payDTO.getOut_trade_no()); try { OrderDTO orderDTO = userService.getOrderByNumber(payDTO.getOut_trade_no()); String productName = orderDTO.getProductName(); BigDecimal amount = orderDTO.getPreAmount(); payRequest.setBody(productName); payRequest.setTotal_fee(amount.multiply(new BigDecimal(100)).intValue()); payRequest.setSpbill_create_ip(request.getRemoteAddr()); payRequest.setNotify_url(WechatConstants.NOTIFY_URL); payRequest.setTrade_type("APP"); payRequest.setAttach("ZHONGHUANBO"); } catch (Exception e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } payRequest.setSign(getSign(payRequest)); //xml XStream xstreamRes = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // CDATA boolean cdata = true; @SuppressWarnings("rawtypes") public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); XStream xstreamReq = new XStream(new XppDriver() /*{ public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // CDATA boolean cdata = true; @SuppressWarnings("rawtypes") public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }*/); xstreamReq.alias("xml", payRequest.getClass()); String requestXML = xstreamReq.toXML(payRequest).replace("\n", "").replace("__", "_"); try { requestXML = new String(requestXML.getBytes("utf-8"), "iso-8859-1"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // BufferedReader reader = null; InputStream is = null; DataOutputStream out = null; StringBuffer sbf = new StringBuffer(); String wechatResponseStr = ""; try { URL url = new URL(WechatConstants.UNIFIED_ORDER_URL); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(requestXML); out.flush(); is = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String strRead = null; while ((strRead = reader.readLine()) != null) { sbf.append(strRead); sbf.append("\r\n"); } wechatResponseStr = sbf.toString(); } catch (Exception e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } finally { try { reader.close(); is.close(); out.close(); } catch (IOException e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } } //? xstreamRes.alias("xml", PayResponse.class); PayResponse payResponse = (PayResponse) xstreamRes.fromXML(wechatResponseStr); //MOCK MODE /*PayResponse payResponse = new PayResponse(); payResponse.setPrepay_id("WX123456789009876543211234567890"); payResponse.setMch_id("6749328409382943"); payResponse.setNonce_str("764932874987392"); payResponse.setTrade_type("APP"); payResponse.setReturn_code("SUCCESS"); payResponse.setResult_code("SUCCESS");*/ if ("SUCCESS".equals(payResponse.getReturn_code()) && "SUCCESS".equals(payResponse.getResult_code())) { payDTO.setMch_id(payResponse.getMch_id()); payDTO.setNonce_str(payResponse.getNonce_str()); payDTO.setPrepay_id(payResponse.getPrepay_id()); payDTO.setTrade_type(payResponse.getTrade_type()); payDTO.setTimestamp(String.valueOf(System.currentTimeMillis() / 1000)); payDTO.setSign(getSignForClient(payDTO)); resultDTO.setBody(payDTO); resultDTO.setCode("0"); resultDTO.setMessage("??"); } else { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } return resultDTO; }
From source file:io.github.protino.codewatch.remote.FetchLeaderBoardData.java
private List<String> fetchLeaderBoardJson() { HttpsURLConnection urlConnection = null; BufferedReader reader = null; List<String> jsonDataList = new ArrayList<>(); try {//from w ww. ja v a 2 s . c o m final String LEADER_PATH = "leaders"; final String API_SUFFIX = "api/v1"; final String API_KEY = "api_key"; final String PAGE = "page"; Uri.Builder builder; String jsonStr; int totalPages = -1; int page = 1; do { builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon(); builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH) .appendQueryParameter(API_KEY, BuildConfig.API_KEY) .appendQueryParameter(PAGE, String.valueOf(page)).build(); URL url = new URL(builder.toString()); // Create the request to Wakatime.com, and open the connection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a string InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } if (buffer.length() == 0) { return null; } jsonStr = buffer.toString(); jsonDataList.add(jsonStr); //parse totalpages if (totalPages == -1) { totalPages = new JSONObject(jsonStr).getInt("total_pages"); } page++; } while (totalPages != page); } catch (IOException e) { Timber.e(e, "IO Error"); } catch (JSONException e) { Timber.e(e, "JSON error"); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); Timber.e(e, "Error closing stream"); } } } return jsonDataList; }
From source file:io.github.protino.codewatch.remote.FetchLeaderBoardData.java
public int fetchUserRank() { AccessToken accessToken = CacheUtils.getAccessToken(context); if (accessToken == null) { return -1; }// www .ja va 2 s . c o m HttpsURLConnection urlConnection = null; BufferedReader reader = null; String jsonStr; try { final String LEADER_PATH = "leaders"; final String API_SUFFIX = "api/v1"; final String CLIENT_SECRET = "secret"; final String APP_SECRET = "app_secret"; final String ACCESS_TOKEN = "token"; Uri.Builder builder; builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon(); builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH) .appendQueryParameter(APP_SECRET, BuildConfig.CLIENT_ID) .appendQueryParameter(CLIENT_SECRET, BuildConfig.CLIENT_SECRET) .appendQueryParameter(ACCESS_TOKEN, accessToken.getAccessToken()).build(); URL url = new URL(builder.toString()); // Create the request to Wakatime.com, and open the connection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a string InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { return -1; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } if (buffer.length() == 0) { return -1; } jsonStr = buffer.toString(); JSONObject currentUser = new JSONObject(jsonStr).getJSONObject("current_user"); if (currentUser == null) { return -1; } else { //if is a new user, it'll result throw JSONException, because rank=null return currentUser.getInt("rank"); } } catch (IOException e) { Timber.e(e, "IO Error"); return -1; } catch (JSONException e) { Timber.e(e, "JSON error"); return -1; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); Timber.e(e, "Error closing stream"); } } } }
From source file:com.flipzu.flipzu.FlipInterface.java
String postViaHttpsConnection(String path, String params) throws IOException { HttpsURLConnection c = null; InputStream is = null;/*from w ww. ja va 2 s . c om*/ OutputStream os = null; String respString = null; int rc; // String url = WSServerSecure + path; URL url = new URL(WSServerSecure + path); try { trustAllHosts(); c = (HttpsURLConnection) url.openConnection(); c.setHostnameVerifier(DO_NOT_VERIFY); c.setDoOutput(true); // Set the request method and headers c.setRequestMethod("POST"); c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); c.setRequestProperty("Content-Language", "en-US"); c.setRequestProperty("Accept-Encoding", "identity"); // Getting the output stream may flush the headers os = c.getOutputStream(); os.write(params.getBytes()); os.flush(); // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. rc = c.getResponseCode(); if (rc != HttpURLConnection.HTTP_OK) { throw new IOException("HTTP response code: " + rc); } is = c.getInputStream(); // Get the length and process the data int len = (int) c.getContentLength(); if (len > 0) { int actual = 0; int bytesread = 0; byte[] data = new byte[len]; while ((bytesread != len) && (actual != -1)) { actual = is.read(data, bytesread, len - bytesread); bytesread += actual; } respString = new String(data); } else { byte[] data = new byte[8192]; int ch; int i = 0; while ((ch = is.read()) != -1) { if (i < data.length) data[i] = ((byte) ch); i++; } respString = new String(data); } } catch (ClassCastException e) { debug.logW(TAG, "Not an HTTP URL"); throw new IllegalArgumentException("Not an HTTP URL"); } finally { if (is != null) is.close(); if (os != null) os.close(); if (c != null) c.disconnect(); } return respString; }
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 ww w .ja va2 s . co 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.echopf.ECHOQuery.java
/** * Sends a HTTP request with optional request contents/parameters. * @param path a request url path/*w w w. j a v a 2s. c om*/ * @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; }