List of usage examples for java.io UnsupportedEncodingException getMessage
public String getMessage()
From source file:com.axibase.tsd.driver.jdbc.content.ContentDescription.java
public String getEncodedQuery() { try {// ww w .j a v a 2 s . c om return URLEncoder.encode(query, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); return query; } }
From source file:com.aliyun.oss.common.comm.HttpFactoryTest.java
@Test public void testCreateHttpRequest() throws Exception { ExecutionContext context = new ExecutionContext(); String url = "http://127.0.0.1"; String content = "This is a test request"; byte[] contentBytes = null; try {/* w ww . ja v a2s . c om*/ contentBytes = content.getBytes(context.getCharset()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); fail(e.getMessage()); } HttpRequestFactory factory = new HttpRequestFactory(); ServiceClient.Request request = new ServiceClient.Request(); request.setUrl(url); HttpRequestBase httpRequest = null; // GET request.setMethod(HttpMethod.GET); httpRequest = factory.createHttpRequest(request, context); HttpGet getMethod = (HttpGet) httpRequest; assertEquals(url, getMethod.getURI().toString()); // DELETE request.setMethod(HttpMethod.DELETE); httpRequest = factory.createHttpRequest(request, context); HttpDelete delMethod = (HttpDelete) httpRequest; assertEquals(url, delMethod.getURI().toString()); // HEAD request.setMethod(HttpMethod.HEAD); httpRequest = factory.createHttpRequest(request, context); HttpHead headMethod = (HttpHead) httpRequest; assertEquals(url, headMethod.getURI().toString()); //POST request.setContent(new ByteArrayInputStream(contentBytes)); request.setContentLength(contentBytes.length); request.setMethod(HttpMethod.POST); httpRequest = factory.createHttpRequest(request, context); HttpPost postMethod = (HttpPost) httpRequest; assertEquals(url, postMethod.getURI().toString()); HttpEntity entity = postMethod.getEntity(); try { assertEquals(content, readSting(entity.getContent())); } catch (IllegalStateException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } //PUT request.setContent(new ByteArrayInputStream(contentBytes)); request.setContentLength(contentBytes.length); request.setMethod(HttpMethod.PUT); httpRequest = factory.createHttpRequest(request, context); HttpPut putMethod = (HttpPut) httpRequest; assertEquals(url, putMethod.getURI().toString()); entity = putMethod.getEntity(); try { assertEquals(content, readSting(entity.getContent())); } catch (IllegalStateException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } try { request.close(); } catch (IOException e) { } }
From source file:com.android.idtt.http.client.RequestParams.java
/** * Returns an HttpEntity containing all request parameters *//* w w w. j ava 2 s . c o m*/ public HttpEntity getEntity() { if (bodyEntity != null) { return bodyEntity; } HttpEntity result = null; if (fileParams != null && !fileParams.isEmpty()) { MultipartEntity multipartEntity = new MultipartEntity(); if (bodyParams != null) { for (NameValuePair param : bodyParams) { try { multipartEntity.addPart(param.getName(), new StringBody(param.getValue())); } catch (UnsupportedEncodingException e) { LogUtils.e(e.getMessage(), e); } } } for (ConcurrentHashMap.Entry<String, ContentBody> entry : fileParams.entrySet()) { multipartEntity.addPart(entry.getKey(), entry.getValue()); } result = multipartEntity; } else if (bodyParams != null) { result = new BodyParamsEntity(bodyParams, charset); } return result; }
From source file:ch.ethz.dcg.jukefox.data.log.LogManager.java
/** * Sends the stored logs to the log server. *///from ww w. ja v a2 s . c o m public void sendLogs() { /* FIXME @Smy: if (!modelSettingsManager.isHelpImproveJukefox()) { return; }*/ // Read the log entries String meId = languageHelper.getUniqueId(); List<PackedLogEntry> logEntries = logProvider.getLogEntryStrings(); int maxLogEntryId = 0; if (logEntries.size() == 0) { // Nothing to do return; } // Pack them to one request StringBuffer sb = new StringBuffer(); sb.append(meId + '\n'); // First line: meId for (PackedLogEntry logEntry : logEntries) { sb.append(logEntry.getPacked()); sb.append('\n'); if (logEntry.getDbLogEntryId() > maxLogEntryId) { maxLogEntryId = logEntry.getDbLogEntryId(); } } String requestStr = sb.toString(); // Send it to the server DefaultHttpClient httpClient = HttpHelper.createHttpClientWithDefaultSettings(); HttpPost httpPost = new HttpPost(Constants.FORMAT_LOG2_URL); try { httpPost.setEntity(new StringEntity(requestStr)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); String serverReply = EntityUtils.toString(response.getEntity()); if ("OK".equals(serverReply)) { logProvider.removeLogEntriesOlderThan(maxLogEntryId); } else { Log.w(TAG, "Could not send the log to the server: " + serverReply); } } catch (UnsupportedEncodingException e) { Log.w(TAG, "Could not build the log to the server package: " + e.getMessage()); } catch (ClientProtocolException e) { Log.w(TAG, "Could not send the log to the server: " + e.getMessage()); } catch (IOException e) { Log.w(TAG, "Could not send the log to the server: " + e.getMessage()); } }
From source file:com.prasanna.android.stacknetwork.service.WriteServiceHelper.java
private Comment writeComment(String restEndPoint, String body) { List<BasicNameValuePair> parameters = getBasicNameValuePartListForPost(); parameters.add(/* w ww .jav a2 s. c o m*/ new BasicNameValuePair(StackUri.QueryParams.FILTER, QueryParamDefaultValues.ITEM_DETAIL_FILTER)); parameters.add(new BasicNameValuePair(StackUri.QueryParams.BODY, body)); Map<String, String> requestHeaders = new HashMap<String, String>(); requestHeaders.put(HttpHeaderParams.CONTENT_TYPE, HttpContentTypes.APPLICATION_FROM_URL_ENCODED); requestHeaders.put(HttpHeaderParams.ACCEPT, HttpContentTypes.APPLICATION_JSON); try { JSONObjectWrapper jsonObject = executeHttpPostRequest(restEndPoint, requestHeaders, null, new UrlEncodedFormEntity(parameters)); JSONArray jsonArray = jsonObject.getJSONArray(JsonFields.ITEMS); if (jsonArray != null && jsonArray.length() == 1) return Comment.parse(JSONObjectWrapper.wrap(jsonArray.getJSONObject(0))); } catch (UnsupportedEncodingException e) { throw new ClientException(ClientException.ClientErrorCode.INVALID_ENCODING); } catch (JSONException e) { LogWrapper.e(TAG, e.getMessage()); } return null; }
From source file:com.meidusa.amoeba.mysql.server.MysqlAuthenticator.java
/** * /*from w w w.j a v a2s . co m*/ */ protected void processAuthentication(AuthingableConnection conn, AuthResponseData rdata) { MysqlClientConnection mysqlConn = (MysqlClientConnection) conn; if (logger.isInfoEnabled()) { logger.info("Accepting request: conn=" + conn); } String errorMessage = ""; try { AuthenticationPacket autheticationPacket = new AuthenticationPacket(); autheticationPacket.init(mysqlConn.getAuthenticationMessage(), conn); mysqlConn.setCharset(CharsetMapping.INDEX_TO_CHARSET[autheticationPacket.charsetNumber & 0xff]); boolean passwordchecked = false; if (logger.isDebugEnabled()) { if (conn.getInetAddress() != null && map.get(conn.getInetAddress().getHostAddress()) == null) { map.put(conn.getInetAddress().getHostAddress(), Boolean.TRUE); long clientParam = autheticationPacket.clientParam; //project.log StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append("===========").append(conn.getInetAddress().getHostAddress()) .append(" Client Flag ==============\n"); builder.append("CLIENT_LONG_PASSWORD:").append(((clientParam & CLIENT_LONG_PASSWORD) != 0)) .append("\n"); builder.append("CLIENT_FOUND_ROWS:").append(((clientParam & CLIENT_FOUND_ROWS) != 0)) .append("\n"); builder.append("CLIENT_LONG_FLAG:").append(((clientParam & CLIENT_LONG_FLAG) != 0)) .append("\n"); builder.append("CLIENT_CONNECT_WITH_DB:").append(((clientParam & CLIENT_CONNECT_WITH_DB) != 0)) .append("\n"); builder.append("CLIENT_NO_SCHEMA:").append(((clientParam & CLIENT_NO_SCHEMA) != 0)) .append("\n"); builder.append("CLIENT_COMPRESS:").append(((clientParam & CLIENT_COMPRESS) != 0)).append("\n"); builder.append("CLIENT_ODBC:").append(((clientParam & CLIENT_ODBC) != 0)).append("\n"); builder.append("CLIENT_LOCAL_FILES:").append(((clientParam & CLIENT_LOCAL_FILES) != 0)) .append("\n"); builder.append("CLIENT_IGNORE_SPACE:").append(((clientParam & CLIENT_IGNORE_SPACE) != 0)) .append("\n"); builder.append("CLIENT_PROTOCOL_41:").append(((clientParam & CLIENT_PROTOCOL_41) != 0)) .append("\n"); builder.append("CLIENT_INTERACTIVE:").append(((clientParam & CLIENT_INTERACTIVE) != 0)) .append("\n"); builder.append("CLIENT_SSL:").append(((clientParam & CLIENT_SSL) != 0)).append("\n"); builder.append("CLIENT_IGNORE_SIGPIPE:").append(((clientParam & CLIENT_IGNORE_SIGPIPE) != 0)) .append("\n"); builder.append("CLIENT_TRANSACTIONS:").append(((clientParam & CLIENT_TRANSACTIONS) != 0)) .append("\n"); builder.append("CLIENT_RESERVED:").append(((clientParam & CLIENT_RESERVED) != 0)).append("\n"); builder.append("CLIENT_SECURE_CONNECTION:") .append(((clientParam & CLIENT_SECURE_CONNECTION) != 0)).append("\n"); builder.append("CLIENT_MULTI_STATEMENTS:") .append(((clientParam & CLIENT_MULTI_STATEMENTS) != 0)).append("\n"); builder.append("CLIENT_MULTI_RESULTS:").append(((clientParam & CLIENT_MULTI_RESULTS) != 0)) .append("\n"); builder.append("===========================END Client Flag===============================\n"); logger.debug(builder.toString()); } } if (mysqlConn.getPassword() != null) { String encryptPassword = new String( Security.scramble411(mysqlConn.getPassword(), mysqlConn.getSeed()), AuthenticationPacket.CODE_PAGE_1252); passwordchecked = StringUtils.equals( new String(autheticationPacket.encryptedPassword, AuthenticationPacket.CODE_PAGE_1252), encryptPassword); } else { if (autheticationPacket.encryptedPassword == null || autheticationPacket.encryptedPassword.length == 0) { passwordchecked = true; } } if (StringUtil.equals(mysqlConn.getUser(), autheticationPacket.user) && passwordchecked) { rdata.code = AuthResponseData.SUCCESS; if (logger.isDebugEnabled()) { logger.debug(autheticationPacket.toString()); } } else { rdata.code = AuthResponseData.ERROR; rdata.message = "Access denied for user '" + autheticationPacket.user + "'@'" + conn.getChannel().socket().getLocalAddress().getHostName() + "'" + (autheticationPacket.encryptedPassword != null ? "(using password: YES)" : ""); } mysqlConn.setSchema(autheticationPacket.database); } catch (UnsupportedEncodingException e) { errorMessage = e.getMessage(); rdata.code = AuthResponseData.ERROR; rdata.message = errorMessage; logger.error("UnsupportedEncodingException error", e); } catch (NoSuchAlgorithmException e) { errorMessage = e.getMessage(); rdata.code = AuthResponseData.ERROR; rdata.message = errorMessage; logger.error("NoSuchAlgorithmException error", e); } catch (Exception e) { errorMessage = e.getMessage(); logger.error("processAuthentication error", e); rdata.code = AuthResponseData.ERROR; rdata.message = errorMessage; } }
From source file:com.fufang.testcase.orgmanager.orgm.SaveOrg.java
@Test public void saveOrg() throws IOException { System.out.println("------start run saveOrg------"); String cookie = getCookie();//ww w.ja va 2s . co m String url = "http://172.16.88.183:9999/organization-manager/orgManager/saveOrg.do"; List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("orderStr", "{\"tpharmacy\":{\"pharmacyCode\":\"101\",\"chainType\":1,\"name\":\"apitest\",\"currency\":1,\"economicType\":0,\"operationMode\":1,\"registeredCapital\":200,\"district\":\"sss\",\"provinceId\":1,\"cityId\":2,\"regionId\":3,\"postalcode\":22,\"registAddress\":\"sds\",\"pharmacyAddress\":\"dsds\",\"phone\":131,\"fax\":\"1313\",\"email\":\"sdfsdf\",\"webAddress\":\"sdfsd\",\"healthInsurancePharmacy\":1,\"representative\":\"ds\",\"businessPrincipal\":\"sds\",\"qualityPrincipal\":\"sds\",\"openBank\":\"sd\",\"openName\":\"sd\",\"accounts\":\"sdsd\",\"ranges\":\"sdfsdf\",\"status\":1,\"remark\":\"sdf\",\"managerDistrict\":\"sdf\",\"manager\":\"dsfd\",\"shopKeeper\":\"sdfds\",\"shopKeeperPhone\":133,\"addPoint\":20,\"distPriceType\":1,\"distPriceOrder\":22,\"priceOrderId\":11,\"settleType\":1,\"unity\":1,\"organizationId\":1,\"shareStorage\":1,\"remoteAudit\":1},\"pharmacyComplement\":{\"healthInsuranceCode\":\"sds\",\"busioption\":\"sd\",\"visible\":1,\"monthlyRent\":121,\"setupShopDate\":\"2016-01-01\",\"recentRelocationDate\":\"2016-01-01\",\"recentTransfDate\":\"2016-01-01\",\"storageArea\":\"12\",\"payProvision\":1,\"payPeriod\":1,\"payPeriodUnit\":1,\"payFrequency\":1,\"payTime\":1,\"pinyin\":\"sds\",\"pharmacyGroupId\":\"5718A378-CB35-452B-A75E-0DCF2DE06665\",\"pharmacyGroup\":\"sd\",\"managerDistrictId\":\"5718A378-CB35-452B-A75E-0DCF2DE05555\",\"ppPurchaserId\":1,\"distrManId\":2,\"ppCheckerId\":3,\"ppReceiverId\":4,\"ppStoremanId\":5,\"ppReCheckerId\":6,\"ppPurchaser\":\"45\",\"distrMan\":\"54\",\"ppChecker\":\"6\",\"ppReceiver\":\"4\",\"ppStoreman\":\"3\",\"ppReChecker\":\"2\",\"inputTax\":0.13,\"outputTax\":0.17},\"pharmacyQualification\":[{\"licenseId\":155,\"licenseCode\":\"assd\",\"validateTo\":\"2016-01-01\",\"fileId\":\"sad\",\"fileName\":\"sdff\"}]}")); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("cookie", cookie); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); InputStream is = null; try { HttpResponse httpResponse = httpClient.execute(httpPost); int status = httpResponse.getStatusLine().getStatusCode(); if (status == 200) { HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { is = httpEntity.getContent(); //?? BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8)); String result = null; while ((result = br.readLine()) != null) { System.out.println(result); JSONObject jsonObject = JSONObject.fromObject(result); int state = jsonObject.getInt("state"); String msg = jsonObject.getString("msg"); Assert.assertEquals(state, 200, "unexpect code"); Assert.assertEquals(msg, "success"); } } } else { System.out.println("Unexpected code - " + status); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); e.getMessage().toString(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); e.getMessage().toString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); e.getMessage().toString(); } finally { httpClient.close(); } }
From source file:com.qut.middleware.esoe.sso.plugins.artifact.data.impl.ArtifactDaoBase.java
public void storeArtifact(Artifact artifact) throws ArtifactBindingException { try {/*from w w w.ja v a 2 s.c o m*/ byte[] base64Bytes = Base64.encodeBase64(artifact.getMessageHandle()); String messageHandle = new String(base64Bytes, "UTF-8"); storeArtifact(artifact, messageHandle); } catch (UnsupportedEncodingException e) { throw new ArtifactBindingException( "Unable to create message handle base64 string, the required encoding is not supported. Error: " + e.getMessage(), e); } }
From source file:org.dataconservancy.ui.it.support.DepositRequest.java
public HttpPost asHttpPost() { if (!dataSetSet) { throw new IllegalStateException("DataItem not set: call setDataSet(DataItem) first."); }/*from w w w .j a v a2s .c om*/ if (fileToDeposit == null) { throw new IllegalStateException("File not set: call setFileToDeposit(File) first"); } if (collectionId == null || collectionId.isEmpty()) { throw new IllegalStateException("Collection id not set: call setCollectionId(String) first."); } if (isUpdate && (dataItemIdentifier == null || dataItemIdentifier.isEmpty())) { throw new IllegalStateException( "Identifer is not set Identifier must be set: callSetDataSetIdentifier or pass in an ID in the constructor"); } if (null == packageId) packageId = ""; String depositUrl = urlConfig.getDepositUrl().toString() + "?redirectUrl=/pages/usercollections.jsp?currentCollectionId=" + collectionId; HttpPost post = new HttpPost(depositUrl); MultipartEntity entity = new MultipartEntity(); try { entity.addPart("currentCollectionId", new StringBody(collectionId, Charset.forName("UTF-8"))); entity.addPart("dataSet.name", new StringBody(name, Charset.forName("UTF-8"))); entity.addPart("dataSet.description", new StringBody(description, Charset.forName("UTF-8"))); entity.addPart("dataSet.id", new StringBody(dataItemIdentifier, Charset.forName("UTF-8"))); entity.addPart("depositPackage.id", new StringBody(packageId, Charset.forName("UTF-8"))); entity.addPart("isContainer", new StringBody(Boolean.valueOf(isContainer()).toString(), Charset.forName("UTF-8"))); if (isUpdate) { entity.addPart("datasetToUpdateId", new StringBody(dataItemIdentifier, Charset.forName("UTF-8"))); entity.addPart(STRIPES_UPDATE_EVENT, new StringBody("Update", Charset.forName("UTF-8"))); } else { entity.addPart(STRIPES_DEPOSIT_EVENT, new StringBody("Deposit", Charset.forName("UTF-8"))); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } FileBody fileBody = new FileBody(fileToDeposit); entity.addPart("uploadedFile", fileBody); post.setEntity(entity); return post; }
From source file:org.prx.prp.utility.HttpHelper.java
private String performRequest(final String contentType, final String url, final String user, final String pass, final Map<String, String> headers, final Map<String, String> params, final int requestType) { if ((user != null) && (pass != null)) { HttpHelper.client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); }/*w w w .ja v a2 s . c om*/ final Map<String, String> sendHeaders = new HashMap<String, String>(); if ((headers != null) && (headers.size() > 0)) { sendHeaders.putAll(headers); } if (requestType == HttpHelper.POST_TYPE) { sendHeaders.put(HttpHelper.CONTENT_TYPE, contentType); } if (sendHeaders.size() > 0) { HttpHelper.client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { for (String key : sendHeaders.keySet()) { if (!request.containsHeader(key)) { request.addHeader(key, sendHeaders.get(key)); } } } }); } HttpRequestBase method = null; if (requestType == HttpHelper.POST_TYPE) { method = new HttpPost(url); List<NameValuePair> nvps = null; if ((params != null) && (params.size() > 0)) { nvps = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } if (nvps != null) { try { HttpPost methodPost = (HttpPost) method; methodPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { Log.d("PRPAND", e.getMessage()); } } } else if (requestType == HttpHelper.GET_TYPE) { String authUrl = url + (url.indexOf('?') != -1 ? '&' : '?') + "key=" + DatabaseHelper.getApiKey(); Log.d("PRPAND", authUrl); method = new HttpGet(authUrl); } return this.execute(method); }