List of usage examples for org.apache.http.entity ContentType create
public static ContentType create(String str, String str2) throws UnsupportedCharsetException
From source file:org.phenotips.remote.server.internal.queuetasks.QueueTaskAsyncAnswer.java
@Override public void run() { try {// w w w.j ava2 s . co m List<PatientSimilarityView> matches = this.patientsFinder .findMatchingPatients(this.request.getRemotePatient()); Map<IncomingSearchRequest, List<PatientSimilarityView>> manyResults = new HashMap<IncomingSearchRequest, List<PatientSimilarityView>>(); manyResults.put(this.request, matches); JSONObject replyJSON = this.apiVersionSpecificConverter.generateAsyncResult(manyResults); CloseableHttpClient client = HttpClients.createDefault(); StringEntity jsonEntity = new StringEntity(replyJSON.toString(), ContentType.create("application/json", "UTF-8")); //String remoteServerId = this.request.getRemoteServerId(); String key = configurationObject.getStringValue(ApplicationConfiguration.CONFIGDOC_REMOTE_KEY_FIELD); String baseURL = configurationObject .getStringValue(ApplicationConfiguration.CONFIGDOC_REMOTE_BASE_URL_FIELD); if (baseURL.charAt(baseURL.length() - 1) != '/') { baseURL += "/"; } String targetURL = baseURL + ApiConfiguration.REMOTE_URL_ASYNCHRONOUS_RESULTS_ENDPOINT; this.logger.error("Sending async results to [" + targetURL + "]: " + replyJSON.toString()); HttpPost httpRequest = new HttpPost(targetURL); httpRequest.setEntity(jsonEntity); httpRequest.setHeader(ApiConfiguration.HTTPHEADER_KEY_PARAMETER, key); client.execute(httpRequest); if (!StringUtils.equalsIgnoreCase(request.getQueryType(), ApiConfiguration.REQUEST_QUERY_TYPE_PERIODIC)) { // remove request form the database if it was a one-tyme async response (as opposed to periodic) this.logger.debug("Removing one-tyme async request from the database (queryID: [{}])", request.getQueryId()); this.requestStorageManager.deleteIncomingPeriodicRequest(request.getQueryId()); } else { // update last results time ((DefaultIncomingSearchRequest) request).setLastResultsTimeToNow(); this.requestStorageManager.updateIncomingPeriodicRequest(request); } } catch (Exception ex) { this.logger.error("Error posting async response: [{}]", ex); } }
From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java
/** * Send request by post method./* w w w . j a v a2 s . co m*/ * * @param uri: * http://ip:port/demo */ public static String doPostJson(String uri, String data) { String result = ""; try { CloseableHttpClient client = null; CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(uri); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.setEntity(new StringEntity(data, ContentType.create("text/json", "UTF-8"))); client = HttpClients.createDefault(); response = client.execute(httpPost); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } finally { if (response != null) { response.close(); } if (client != null) { client.close(); } } } catch (Exception e) { e.printStackTrace(); LOG.error("Do post json request has error, msg is " + e.getMessage()); } return result; }
From source file:de.freegroup.twogo.plotter.rpc.Client.java
private String getToken(CloseableHttpClient httpclient) throws Exception { RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost request = new HttpPost(this.serverUrl + "Echo"); request.setConfig(config);/* ww w . j a v a 2 s . co m*/ request.setHeader("Content-Type", "text/plain"); request.setHeader("X-CSRF-Token", "Fetch"); try { JSONObject message = buildParam("echo", new String[] { "any" }); StringEntity body = new StringEntity(message.toString(), ContentType.create("application/json", Consts.UTF_8)); request.setEntity(body); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); CloseableHttpResponse response = httpclient.execute(request); JSONTokener tokener = new JSONTokener(new BasicResponseHandler().handleResponse(response)); Object rawResponseMessage = tokener.nextValue(); JSONObject responseMessage = (JSONObject) rawResponseMessage; if (responseMessage == null) { throw new ClientError("Invalid response type - " + rawResponseMessage.getClass()); } return (responseMessage.getJSONObject("result").getJSONObject("header").getString("value")); } catch (Exception e) { throw new ClientError(e); } }
From source file:nya.miku.wishmaster.http.ExtendedMultipartBuilder.java
/** * ? UTF-8// w w w. java2 s . com * @param key ? () * @param value ? * @return ? */ public ExtendedMultipartBuilder addString(String key, String value) { return addPart(key, new StringBody(value, ContentType.create("text/plain", "UTF-8"))); }
From source file:org.apache.manifoldcf.jettyrunner.ManifoldCFJettyShutdown.java
public void shutdownJetty() throws Exception { // Pick up shutdown token String shutdownToken = System.getProperty("org.apache.manifoldcf.jettyshutdowntoken"); if (shutdownToken != null) { int socketTimeout = 900000; int connectionTimeout = 300000; HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(false) .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); HttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1) .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()).build(); HttpPost method = new HttpPost( jettyBaseURL + "/shutdown?token=" + URLEncoder.encode(shutdownToken, "UTF-8")); method.setEntity(new StringEntity("", ContentType.create("text/plain", StandardCharsets.UTF_8))); try {/*from w w w .j av a2 s . c o m*/ HttpResponse httpResponse = httpClient.execute(method); int resultCode = httpResponse.getStatusLine().getStatusCode(); if (resultCode != 200) throw new Exception("Received result code " + resultCode + " from POST"); } catch (org.apache.http.NoHttpResponseException e) { // This is ok and expected } } else { throw new Exception("No jetty shutdown token specified"); } }
From source file:org.sasabus.export2Freegis.network.SubscriptionManager.java
public boolean subscribe() throws IOException { for (int i = 0; i < SUBFILEARRAY.length; ++i) { Scanner sc = new Scanner(new File(SUBFILEARRAY[i])); String subscriptionstring = ""; while (sc.hasNextLine()) { subscriptionstring += sc.nextLine(); }//from w w w. j ava2s. c o m sc.close(); SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ"); Date d = new Date(); String timestamp = date_date.format(d) + "T" + date_time.format(d); timestamp = timestamp.substring(0, timestamp.length() - 2) + ":" + timestamp.substring(timestamp.length() - 2); Calendar c = Calendar.getInstance(); c.setTime(d); c.add(Calendar.DATE, 1); d = c.getTime(); String valid_until = date_date.format(d) + "T" + date_time.format(d); valid_until = valid_until.substring(0, valid_until.length() - 2) + ":" + valid_until.substring(valid_until.length() - 2); subscriptionstring = subscriptionstring.replaceAll(":timestamp_valid", valid_until); subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp); String requestString = "http://" + this.address + ":" + this.portnumber_sender + "/TmEvNotificationService/gms/subscription.xml"; HttpPost subrequest = new HttpPost(requestString); StringEntity requestEntity = new StringEntity(subscriptionstring, ContentType.create("text/xml", "ISO-8859-1")); CloseableHttpClient httpClient = HttpClients.createDefault(); subrequest.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(subrequest); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { try { System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode()); System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase()); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responsebody = EntityUtils.toString(responseEntity); System.out.println(responsebody); } } finally { response.close(); httpClient.close(); } return false; } System.out.println("Subscription of " + SUBFILEARRAY[i]); } return true; }
From source file:edu.jhuapl.dorset.http.apache.ApacheHttpClient.java
private Response post(HttpRequest request) throws IOException { Request apacheRequest = Request.Post(request.getUrl()); if (request.getBody() != null) { ContentType ct = ContentType.create(request.getContentType().getMimeType(), request.getContentType().getCharset()); apacheRequest.bodyString(request.getBody(), ct); } else if (request.getBodyForm() != null) { apacheRequest.bodyForm(buildFormBody(request.getBodyForm())); }// ww w . j a v a 2 s . co m prepareRequest(apacheRequest); return apacheRequest.execute(); }
From source file:com.huawei.ais.demo.TokenDemo.java
/** * Base64???Token???// w w w . java 2 s .c o m * @param token token? * @param formFile * @throws IOException */ public static void requestOcrCustomsFormEnBase64(String token, String formFile) { // 1.????? String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/action/ocr_form"; Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token) }; try { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody fileBody = new FileBody(new File(formFile), ContentType.create("image/jpeg", "utf-8")); multipartEntityBuilder.addPart("file", fileBody); // 2.????, POST?? HttpResponse response = HttpClientUtils.post(url, headers, multipartEntityBuilder.build()); System.out.println(response); String content = IOUtils.toString(response.getEntity().getContent()); System.out.println(content); } catch (Exception e) { e.printStackTrace(); } }
From source file:io.liveoak.pgsql.BasePgSqlHttpTest.java
protected String postRequest(HttpPost post, String json) throws IOException { StringEntity entity = new StringEntity(json, ContentType.create(APPLICATION_JSON, "UTF-8")); post.setEntity(entity);/*w w w . j a va2 s .c om*/ System.err.println("DO POST - " + post.getURI()); System.out.println("\n" + json); CloseableHttpResponse result = httpClient.execute(post); System.err.println("=============>>>"); System.err.println(result); HttpEntity resultEntity = result.getEntity(); assertThat(resultEntity.getContentLength()).isGreaterThan(0); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resultEntity.writeTo(baos); String resultStr = new String(baos.toByteArray()); System.err.println(resultStr); System.err.println("\n<<<============="); return resultStr; }
From source file:org.pepstock.jem.node.https.HttpJobListener.java
@Override public void ended(Job job) { // if job is not waiting, return if (job.isNowait()) { return;//from w ww .ja va2 s .c om } // if there is the IP address // to reply if (job.getInputArguments() != null && job.getInputArguments().contains(SubmitHandler.JOB_SUBMIT_IP_ADDRESS_KEY)) { // creates the URL // the path is always the JOBID String url = "http://" + job.getInputArguments().get(0) + ":" + job.getInputArguments().get(1) + "/" + job.getId(); // creates a HTTP client CloseableHttpClient httpclient = null; try { httpclient = HttpUtil.createHttpClient(url); // gets if printoutput is required boolean printOutput = Parser.parseBoolean(job.getInputArguments().get(2), false); // creates the response // ALWAYS the return code StringBuilder sb = new StringBuilder(); sb.append(job.getResult().getReturnCode()).append("\n"); // if client needs output // it adds teh output of job if (printOutput) { File file = Main.getOutputSystem().getMessagesLogFile(job); sb.append(FileUtils.readFileToString(file)); } // creates teh HTTP entity StringEntity entity = new StringEntity(sb.toString(), ContentType.create("text/plain", CharSet.DEFAULT_CHARSET_NAME)); // prepares POST request and basic response handler HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); // executes and no parsing // result must be only a string CloseableHttpResponse response = httpclient.execute(httppost); response.close(); return; } catch (Exception e) { LogAppl.getInstance().emit(NodeMessage.JEMC289E, e, job.getInputArguments().get(0) + ":" + job.getInputArguments().get(1), job.toString()); } finally { // close http client if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { LogAppl.getInstance().ignore(e.getMessage(), e); } } } } }