List of usage examples for java.io UnsupportedEncodingException printStackTrace
public void printStackTrace()
From source file:com.smallchill.core.toolbox.Func.java
public static String decodeUrl(String url) { try {//from www.j a va 2 s . c o m url = isEmpty(url) ? "" : url; url = URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return url; }
From source file:com.thoughtmetric.tl.TLLib.java
public static boolean login(String login, String pw, Handler handler, Context context) throws IOException { handler.sendEmptyMessage(TLHandler.PROGRESS_LOGIN); // Fetch the token HtmlCleaner cleaner = TLLib.buildDefaultHtmlCleaner(); URL url = new URL(LOGIN_URL); TagNode node = TLLib.TagNodeFromURLLoginToken(cleaner, url, handler, context); String token = null;//from ww w .j ava2 s . co m try { TagNode result = (TagNode) node.evaluateXPath("//input")[0]; token = result.getAttributeByName("value"); } catch (XPatherException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (token == null) { return false; } // DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpost = new HttpPost(LOGIN_URL); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(USER_FIELD, login)); nvps.add(new BasicNameValuePair(PASS_FIELD, pw)); nvps.add(new BasicNameValuePair(REMEMBERME, "1")); nvps.add(new BasicNameValuePair("stage", "1")); nvps.add(new BasicNameValuePair("back_url", "")); nvps.add(new BasicNameValuePair("token", token)); Log.d("token:", token); try { httpost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); Header[] headers = response.getHeaders("Set-Cookie"); if (headers.length > 0) { loginName = null; loginStatus = false; } else { loginName = login; loginStatus = true; cookieStore = httpclient.getCookieStore(); } if (entity != null) { entity.consumeContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return loginStatus; }
From source file:com.android.providers.downloads.OmaDownload.java
/** * This method notifies the server for the status of the download operation. * It sends a status report to a Web server if installNotify attribute is specified in the download descriptor. @param component the component that contains attributes in the descriptor. @param handler the handler used to send and process messages. A message indicates whether the media object is available to the user or not (READY or DISCARD). *///from ww w . j av a 2 s .c o m //protected static void installNotify (OmaDescription component, Handler handler) { protected static int installNotify(OmaDescription component, Handler handler) { int ack = -1; int release = OmaStatusHandler.DISCARD; URL url = component.getInstallNotifyUrl(); if (url != null) { DefaultHttpClient client = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url.toString()); try { HttpParams params = postRequest.getParams(); HttpProtocolParams.setUseExpectContinue(params, false); postRequest.setEntity( new StringEntity(OmaStatusHandler.statusCodeToString(component.getStatusCode()) + "\n\r")); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // TODO Auto-generated method stub Log.i("@M_" + Constants.LOG_OMA_DL, "Retry the request..."); return (executionCount <= OmaStatusHandler.MAXIMUM_RETRY); } }); try { HttpResponse response = client.execute(postRequest); if (response.getStatusLine() != null) { ack = response.getStatusLine().getStatusCode(); //200-series response code if (ack == HttpStatus.SC_OK || ack == HttpStatus.SC_ACCEPTED || ack == HttpStatus.SC_CREATED || ack == HttpStatus.SC_MULTI_STATUS || ack == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION || ack == HttpStatus.SC_NO_CONTENT || ack == HttpStatus.SC_PARTIAL_CONTENT || ack == HttpStatus.SC_RESET_CONTENT) { if (component.getStatusCode() == OmaStatusHandler.SUCCESS) { release = OmaStatusHandler.READY; } } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); if (inputStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String s; while ((s = br.readLine()) != null) { Log.v("@M_" + Constants.LOG_OMA_DL, "Response: " + s); } } } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } } catch (ConnectTimeoutException e) { Log.e("@M_" + Constants.LOG_OMA_DL, e.toString()); postRequest.abort(); //After time out period, the client releases the media object for use. if (component.getStatusCode() == OmaStatusHandler.SUCCESS) { release = OmaStatusHandler.READY; } } catch (NoHttpResponseException e) { Log.e("@M_" + Constants.LOG_OMA_DL, e.toString()); postRequest.abort(); //After time out period, the client releases the media object for use. if (component.getStatusCode() == OmaStatusHandler.SUCCESS) { release = OmaStatusHandler.READY; } } catch (IOException e) { Log.e("@M_" + Constants.LOG_OMA_DL, e.toString()); postRequest.abort(); } if (client != null) { client.getConnectionManager().shutdown(); } } else { if (component.getStatusCode() == OmaStatusHandler.SUCCESS) { release = OmaStatusHandler.READY; } } if (handler != null) { Message mg = Message.obtain(); mg.arg1 = release; handler.sendMessage(mg); } return release; }
From source file:com.baidu.rigel.biplatform.ac.util.HttpRequest.java
/** * URL???? key=value&key=value?//from w ww . j a va 2s.c o m * * @param url url * @param params ? * @return ?? */ private static List<String> checkUrlAndWrapParam(String url, Map<String, String> params, boolean uriEncoder) { if (StringUtils.isBlank(url)) { throw new IllegalArgumentException("can not send get by null url"); } List<String> paramList = new ArrayList<String>(); if (MapUtils.isNotEmpty(params)) { for (Map.Entry<String, String> entry : params.entrySet()) { if (StringUtils.isBlank(entry.getKey()) || StringUtils.isBlank(entry.getValue())) { continue; } else { String value = entry.getValue(); if (uriEncoder) { try { value = URLEncoder.encode(value, "utf-8"); } catch (UnsupportedEncodingException e) { LOGGER.warn("encode value:" + value + "error"); e.printStackTrace(); } } paramList.add(entry.getKey() + "=" + value); } } } return paramList; }
From source file:com.lvwallpapers.utils.WebServiceUtils.java
public static Photo handleResult(String photoId) { String result = null;// w w w. j av a 2s.c o m try { Log.e("URL DSAHDKJA", getWeb_Url(photoId)); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpGet(getWeb_Url(photoId)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); if (result != null && result.length() > 0) { JSONObject jobject = new JSONObject(result); String state = jobject.getString("stat"); if (state.equalsIgnoreCase(STAT_OK)) { // Photo Object String photo = jobject.getString("photo"); JSONObject jobjectPhoto = new JSONObject(photo); String id = jobjectPhoto.getString("id"); String secret = jobjectPhoto.getString("secret"); String server = jobjectPhoto.getString("server"); String farm = jobjectPhoto.getString("farm"); String license = jobjectPhoto.getString("license"); String originalsecret = "", originalformat = ""; if (jobjectPhoto.has("originalsecret")) { originalsecret = jobjectPhoto.getString("originalsecret"); originalformat = jobjectPhoto.getString("originalformat"); } // Author Object String owner = jobjectPhoto.getString("owner"); JSONObject jobjectOwner = new JSONObject(owner); String nsid = jobjectOwner.getString("nsid"); String username = jobjectOwner.getString("username"); String realname = jobjectOwner.getString("realname"); String iconFarm = "", iconServer = ""; if (jobjectOwner.has("iconfarm")) { iconFarm = jobjectOwner.getString("iconfarm"); } if (jobjectOwner.has("iconserver")) { iconServer = jobjectOwner.getString("iconserver"); } // Title Object String titleObject = jobjectPhoto.getString("title"); JSONObject jobjectTitle = new JSONObject(titleObject); String title = jobjectTitle.getString("_content"); // Description Object String desObject = jobjectPhoto.getString("description"); JSONObject jobjectDescription = new JSONObject(desObject); String description = jobjectDescription.getString("_content"); // Local Object String location = "", locality = "", region = "", country = ""; if (jobjectPhoto.has("location")) { location = jobjectPhoto.getString("location"); JSONObject jobjectLocation = new JSONObject(location); // Locality String localityObject = ""; if (jobjectLocation.has("locality")) { localityObject = jobjectLocation.getString("locality"); JSONObject jobjectlocality = new JSONObject(localityObject); locality = jobjectlocality.getString("_content"); } // Region if (jobjectLocation.has("region")) { String regionObject = jobjectLocation.getString("region"); JSONObject jobjectregion = new JSONObject(regionObject); region = jobjectregion.getString("_content"); } // Country if (jobjectLocation.has("country")) { String countryObject = jobjectLocation.getString("country"); JSONObject jobjectcountry = new JSONObject(countryObject); country = jobjectcountry.getString("_content"); } } String url = ""; if (jobjectPhoto.has("urls")) { String urls = jobjectPhoto.getString("urls"); JSONObject jobjectUrls = new JSONObject(urls); if (jobjectUrls.has("url")) { String arrayUrlObject = jobjectUrls.getString("url"); JSONArray jarraytUrl = new JSONArray(arrayUrlObject); JSONObject jsonObjectUrl = jarraytUrl.getJSONObject(0); if (jsonObjectUrl.has("_content")) url = jsonObjectUrl.getString("_content"); } } Photo photoObject = new Photo(id, secret, server, farm, license, originalsecret, originalformat, nsid, username, realname, title, description, locality, region, country, url, iconServer, iconFarm, false, ""); return photoObject; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; }
From source file:org.opensourcetlapp.tl.TLLib.java
public static void subscribeThread(String topicId) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setCookieStore(cookieStore); HttpPost httpost = new HttpPost(SUB_URL); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("action", "toggleSub")); nvps.add(new BasicNameValuePair("thread_id", topicId)); nvps.add(new BasicNameValuePair("token", tokenField)); Log.d(TAG, "Subscribing Thread"); try {/*from www . jav a 2 s .c om*/ httpost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } }
From source file:org.opensourcetlapp.tl.TLLib.java
public static void postMessage(String message, String backurl, String topicId, Context context) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setCookieStore(cookieStore); HttpPost httpost = new HttpPost(POST_URL); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("bericht", message)); nvps.add(new BasicNameValuePair("stage", "1")); nvps.add(new BasicNameValuePair("backurl", backurl)); nvps.add(new BasicNameValuePair("token", tokenField)); nvps.add(new BasicNameValuePair("topic_id", topicId)); nvps.add(new BasicNameValuePair("submit_button", "Post")); try {/*from w w w . j av a 2 s .co m*/ httpost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } }
From source file:org.opensourcetlapp.tl.TLLib.java
public static void sendPM(String to, String subject, String message) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setCookieStore(cookieStore); HttpPost httpost = new HttpPost(PM_URL); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("to", to)); nvps.add(new BasicNameValuePair("subject", subject)); nvps.add(new BasicNameValuePair("body", message)); nvps.add(new BasicNameValuePair("view", "Send")); nvps.add(new BasicNameValuePair("token", tokenField)); Log.d(TAG, "Sending message"); Log.d(TAG, to);// w ww. ja v a2 s .c o m Log.d(TAG, subject); Log.d(TAG, message); try { httpost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } }
From source file:com.jpeterson.littles3.S3ObjectRequest.java
/** * Create an <code>S3Object</code> based on the request supporting virtual * hosting of buckets./*from w ww . j a va 2s . co m*/ * * @param req * The original request. * @param baseHost * The <code>baseHost</code> is the HTTP Host header that is * "expected". This is used to help determine how the bucket name * will be interpreted. This is used to implement the "Virtual * Hosting of Buckets". * @param authenticator * The authenticator to use to authenticate this request. * @return An object initialized from the request. * @throws IllegalArgumentException * Invalid request. */ @SuppressWarnings("unchecked") public static S3ObjectRequest create(HttpServletRequest req, String baseHost, Authenticator authenticator) throws IllegalArgumentException, AuthenticatorException { S3ObjectRequest o = new S3ObjectRequest(); String pathInfo = req.getPathInfo(); String contextPath = req.getContextPath(); String requestURI = req.getRequestURI(); String undecodedPathPart = null; int pathInfoLength; String requestURL; String serviceEndpoint; String bucket = null; String key = null; String host; String value; String timestamp; baseHost = baseHost.toLowerCase(); host = req.getHeader("Host"); if (host != null) { host = host.toLowerCase(); } try { requestURL = URLDecoder.decode(req.getRequestURL().toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { // should never happen e.printStackTrace(); IllegalArgumentException t = new IllegalArgumentException("Unsupport encoding: UTF-8"); t.initCause(e); throw t; } if (!requestURL.endsWith(pathInfo)) { String m = "requestURL [" + requestURL + "] does not end with pathInfo [" + pathInfo + "]"; throw new IllegalArgumentException(m); } pathInfoLength = pathInfo.length(); serviceEndpoint = requestURL.substring(0, requestURL.length() - pathInfoLength); if (debug) { System.out.println("---------------"); System.out.println("requestURI: " + requestURI); System.out.println("serviceEndpoint: " + serviceEndpoint); System.out.println("---------------"); } if ((host == null) || // http 1.0 form (host.equals(baseHost))) { // ordinary method // http 1.0 form // bucket first part of path info // key second part of path info if (pathInfoLength > 1) { int index = pathInfo.indexOf('/', 1); if (index > -1) { bucket = pathInfo.substring(1, index); if (pathInfoLength > (index + 1)) { key = pathInfo.substring(index + 1); undecodedPathPart = requestURI.substring(contextPath.length() + 1 + bucket.length(), requestURI.length()); } } else { bucket = pathInfo.substring(1); } } } else if (host.endsWith("." + baseHost)) { // bucket prefix of host // key is path info bucket = host.substring(0, host.length() - 1 - baseHost.length()); if (pathInfoLength > 1) { key = pathInfo.substring(1); undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length()); } } else { // bucket is host // key is path info bucket = host; if (pathInfoLength > 1) { key = pathInfo.substring(1); undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length()); } } // timestamp timestamp = req.getHeader("Date"); // CanonicalizedResource StringBuffer canonicalizedResource = new StringBuffer(); canonicalizedResource.append('/'); if (bucket != null) { canonicalizedResource.append(bucket); } if (undecodedPathPart != null) { canonicalizedResource.append(undecodedPathPart); } if (req.getParameter(PARAMETER_ACL) != null) { canonicalizedResource.append("?").append(PARAMETER_ACL); } // CanonicalizedAmzHeaders StringBuffer canonicalizedAmzHeaders = new StringBuffer(); Map<String, String> headers = new TreeMap<String, String>(); String headerName; String headerValue; for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) { headerName = ((String) headerNames.nextElement()).toLowerCase(); if (headerName.startsWith("x-amz-")) { for (Enumeration headerValues = req.getHeaders(headerName); headerValues.hasMoreElements();) { headerValue = (String) headerValues.nextElement(); String currentValue = headers.get(headerValue); if (currentValue != null) { // combine header fields with the same name headers.put(headerName, currentValue + "," + headerValue); } else { headers.put(headerName, headerValue); } if (headerName.equals("x-amz-date")) { timestamp = headerValue; } } } } for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) { headerName = iter.next(); headerValue = headers.get(headerName); canonicalizedAmzHeaders.append(headerName).append(":").append(headerValue).append("\n"); } StringBuffer stringToSign = new StringBuffer(); stringToSign.append(req.getMethod()).append("\n"); value = req.getHeader("Content-MD5"); if (value != null) { stringToSign.append(value); } stringToSign.append("\n"); value = req.getHeader("Content-Type"); if (value != null) { stringToSign.append(value); } stringToSign.append("\n"); value = req.getHeader("Date"); if (value != null) { stringToSign.append(value); } stringToSign.append("\n"); stringToSign.append(canonicalizedAmzHeaders); stringToSign.append(canonicalizedResource); if (debug) { System.out.println(":v:v:v:v:"); System.out.println("undecodedPathPart: " + undecodedPathPart); System.out.println("canonicalizedAmzHeaders: " + canonicalizedAmzHeaders); System.out.println("canonicalizedResource: " + canonicalizedResource); System.out.println("stringToSign: " + stringToSign); System.out.println(":^:^:^:^:"); } o.setServiceEndpoint(serviceEndpoint); o.setBucket(bucket); o.setKey(key); try { if (timestamp == null) { o.setTimestamp(null); } else { o.setTimestamp(DateUtil.parseDate(timestamp)); } } catch (DateParseException e) { o.setTimestamp(null); } o.setStringToSign(stringToSign.toString()); o.setRequestor(authenticate(req, o)); return o; }
From source file:de.tudarmstadt.ukp.wikipedia.parser.html.HtmlWriter.java
public static void writeFile(String filename, String encoding, String text) { File outFile = new File(filename); Writer destFile = null;/*from w ww. j a v a 2s .c o m*/ try { destFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), encoding)); } catch (UnsupportedEncodingException e1) { logger.error("Unsupported encoding exception while opening file " + outFile.getAbsolutePath()); e1.printStackTrace(); } catch (FileNotFoundException e1) { logger.error("File " + outFile.getAbsolutePath() + " not found."); e1.printStackTrace(); } try { destFile.write(text); } catch (IOException e) { logger.error("IO exception while writing file " + outFile.getAbsolutePath()); e.printStackTrace(); } try { destFile.close(); } catch (IOException e) { logger.error("IO exception while closing file " + outFile.getAbsolutePath()); e.printStackTrace(); } }