List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:org.wso2.am.integration.tests.other.HttpPATCHSupportTestCase.java
@Test(groups = "wso2.am", description = "Check functionality of HTTP PATCH support for APIM") public void testHttpPatchSupport() throws Exception { //Login to the API Publisher apiPublisher.login(user.getUserName(), user.getPassword()); String APIName = "HttpPatchAPI"; String APIContext = "patchTestContext"; String url = getGatewayURLNhttp() + "httpPatchSupportContext"; String providerName = user.getUserName(); String APIVersion = "1.0.0"; APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); apiRequest.setVersion(APIVersion);//ww w. jav a 2 s.c o m apiRequest.setProvider(providerName); //Adding the API to the publisher apiPublisher.addAPI(apiRequest); //Publish the API APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); apiPublisher.changeAPILifeCycleStatus(updateRequest); String modifiedResource = "{\"paths\":{ \"/*\":{\"patch\":{ \"responses\":{\"200\":{}},\"x-auth-type\":\"Application\"," + "\"x-throttling-tier\":\"Unlimited\" },\"get\":{ \"responses\":{\"200\":{}},\"x-auth-type\":\"Application\"," + "\"x-throttling-tier\":\"Unlimited\",\"x-scope\":\"user_scope\"}}},\"swagger\":\"2.0\",\"info\":{\"title\":\"HttpPatchAPI\",\"version\":\"1.0.0\"}," + "\"x-wso2-security\":{\"apim\":{\"x-wso2-scopes\":[{\"name\":\"admin_scope\",\"description\":\"\",\"key\":\"admin_scope\",\"roles\":\"admin\"}," + "{\"name\":\"user_scope\",\"description\":\"\",\"key\":\"user_scope\",\"roles\":\"admin,subscriber\"}]}}}"; //Modify the resources to add the PATCH resource method to the API apiPublisher.updateResourceOfAPI(providerName, APIName, APIVersion, modifiedResource); //Login to the API Store apiStore.login(user.getUserName(), user.getPassword()); //Add an Application in the Store. apiStore.addApplication("HttpPatchSupportAPP", APIMIntegrationConstants.APPLICATION_TIER.LARGE, "", "Test-HTTP-PATCH"); //Subscribe to the new application SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, APIVersion, providerName, "HttpPatchSupportAPP", APIMIntegrationConstants.API_TIER.GOLD); apiStore.subscribe(subscriptionRequest); //Generate a production token and invoke the API APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("HttpPatchSupportAPP"); String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); JSONObject jsonResponse = new JSONObject(responseString); //Get the accessToken generated. String accessToken = jsonResponse.getJSONObject("data").getJSONObject("key").getString("accessToken"); String apiInvocationUrl = getAPIInvocationURLHttp(APIContext, APIVersion); //Invoke the API by sending a PATCH request; HttpClient client = HttpClientBuilder.create().build(); HttpPatch request = new HttpPatch(apiInvocationUrl); request.setHeader("Accept", "application/json"); request.setHeader("Authorization", "Bearer " + accessToken); StringEntity payload = new StringEntity("{\"first\":\"Greg\"}", "UTF-8"); payload.setContentType("application/json"); request.setEntity(payload); HttpResponse httpResponsePatch = client.execute(request); //Assertion assertEquals(httpResponsePatch.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(), "The response code is not 200 OK"); }
From source file:org.ow2.proactive.procci.service.RequestUtils.java
/** * Send a service to pca service with a header containing the session id and sending content * * @param content is which is send to the cloud automation service * @return the information about gathered from cloud automation service *//*from www. ja v a 2 s. com*/ public JSONObject postRequest(JSONObject content, String url) { final String PCA_SERVICE_SESSIONID = "sessionid"; try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost postRequest = new HttpPost(url); postRequest.addHeader(PCA_SERVICE_SESSIONID, getSessionId()); StringEntity input = new StringEntity(content.toJSONString()); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); String serverOutput = readHttpResponse(response, url, "POST " + content.toJSONString()); return parseJSON(serverOutput); } catch (IOException ex) { logger.error(" IO exception in CloudAutomationInstanceClient::postRequest ", ex); throw new ServerException(); } }
From source file:diuf.unifr.ch.first.xwot.notifications.LockNotificationBuilder.java
/** * Encode into xml the Lock JAXB class//from w w w. j a v a 2s . c o m * * @see Lock * @param client * @return instance of a StringEntity containg xml informations */ @Override public StringEntity jaxbToStringEntity(Client client) { StringEntity body = null; if (lock == null || !lock.equalsToLock(oldLock)) { setLock(); } try { body = new StringEntity(jaxbToXml(Lock.class, lock)); body.setContentType("application/xml"); } catch (UnsupportedEncodingException ex) { logger.error("Unable to encode StringEntity", ex); } return body; }
From source file:IoTatWork.NotifyResolutionManager.java
/** * //from www . ja va 2 s. c o m * @param notification * @return */ private boolean sendNotification(PendingResolutionNotification notification) { String xmlString = notification.toXML(); String revocationPut = notification.getNotificationUrl() + notification.getRevocationHash(); System.out.println("\nProcessing notification: " + revocationPut + "\n" + notification.toXML()); // TODO logEvent //IoTatWorkApplication.logger.info("Sending pending resolution notification: "+revocationPut); IoTatWorkApplication.logger.info(LogMessage.SEND_RESOLUTION_NOTIFICATION + revocationPut); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPut putRequest = new HttpPut(revocationPut); try { StringEntity input = new StringEntity(xmlString); input.setContentType("application/xml"); putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case 200: IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_200); break; case 400: BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output = br.toString(); /* while ((output = br.readLine()) != null) { System.out.println(output); } */ JsonParser parser = new JsonParser(); JsonObject jsonObj = (JsonObject) parser.parse(output); String code = jsonObj.get(JSON_PROCESSING_STATUS_CODE).getAsString(); if (code.equals("NPR400")) { IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_400); } else if (code.equals("NPR450")) { IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_450); } else if (code.equals("NPR451")) { IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_451); } break; case 404: IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_404); break; case 500: IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_500); break; default: break; } httpClient.getConnectionManager().shutdown(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }
From source file:org.caratarse.auth.services.controller.UserAuthorizationControllerTest.java
@Test public void addAuthorizationToUser() throws UnsupportedEncodingException, IOException { HttpPost postRequest = new HttpPost( BASE_URL + "/users/a1ab82a6-c8ce-4723-8532-777c4b05d03c/authorizations/ROLE_NOT_USED.json"); StringEntity input = new StringEntity( "{\"permissions\":{ \"read\": true, \"write\": false, \"execute\": true}}"); input.setContentType("application/json"); postRequest.setEntity(input);//w w w. j a v a2 s. co m HttpResponse response = httpClient.execute(postRequest); assertEquals(201, response.getStatusLine().getStatusCode()); log.debug(IOUtils.toString(response.getEntity().getContent())); }
From source file:com.couchbase.lite.performance.Test7_PullReplication.java
private void pushDocumentToSyncGateway(String docId, final String docJson) throws MalformedURLException { // push a document to server URL replicationUrlTrailingDoc1 = new URL( String.format("%s/%s", getReplicationURL().toExternalForm(), docId)); final URL pathToDoc1 = new URL(replicationUrlTrailingDoc1, docId); Log.d(TAG, "Send http request to " + pathToDoc1); final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1); BackgroundTask getDocTask = new BackgroundTask() { @Override//w w w . ja va 2 s . c om public void run() { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; String responseString = null; try { HttpPut post = new HttpPut(pathToDoc1.toExternalForm()); StringEntity se = new StringEntity(docJson.toString()); se.setContentType(new BasicHeader("content_type", "application/json")); post.setEntity(se); response = httpclient.execute(post); StatusLine statusLine = response.getStatusLine(); Log.d(TAG, "Got response: " + statusLine); assertTrue(statusLine.getStatusCode() == HttpStatus.SC_CREATED); } catch (ClientProtocolException e) { assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e); } catch (IOException e) { assertNull("Got IOException: " + e.getLocalizedMessage(), e); } httpRequestDoneSignal.countDown(); } }; getDocTask.execute(); Log.d(TAG, "Waiting for http request to finish"); try { httpRequestDoneSignal.await(300, TimeUnit.SECONDS); Log.d(TAG, "http request finished"); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:com.xively.client.http.DefaultRequestHandler.java
private <T extends DomainObject> StringEntity getEntity(boolean isUpdate, T... bodyObjects) { AcceptedMediaType mediaType = AppConfig.getInstance().getResponseMediaType(); String json = ParserUtil.toJson(isUpdate, bodyObjects); DefaultRequestHandler.log.debug("Sending: \n" + json); StringEntity body = null; try {/*from ww w . j ava 2 s. c o m*/ body = new StringEntity(json); body.setContentType(mediaType.getMediaType()); } catch (UnsupportedEncodingException e) { throw new RequestInvalidException("Unable to encode json string for making request.", e); } return body; }
From source file:edu.pdx.its.portal.routelandia.ApiPoster.java
public JSONObject postJsonObjectToUrl(String url, JSONObject jsonObject, APIResultWrapper retVal) { InputStream inputStream = null; String result = ""; try {// w w w. j a va 2s.c om // 1. create HttpClient HttpClient httpclient = new DefaultHttpClient(); // 2. make POST request to the given URL //http://capstoneaa.cs.pdx.edu/api/trafficstats HttpPost httpPost = new HttpPost(url); // 4. convert JSONObject to JSON to String String json = jsonObject.toString(); // 5. set json to StringEntity StringEntity se = new StringEntity(json); se.setContentType("application/json;charset=UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); // 6. set httpPost Entity httpPost.setEntity(se); // 7. Set some headers to inform server about the type of the content // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // 8. Execute POST request to the given URL HttpResponse httpResponse = httpclient.execute(httpPost); // Make sure we've got a good response from the API. int status = httpResponse.getStatusLine().getStatusCode(); retVal.setHttpStatus(status); result = EntityUtils.toString(httpResponse.getEntity()); //Log.i("RAW HTTP RESULT", result); retVal.setRawResponse(result); } catch (Exception e) { Log.e("InputStream", e.getLocalizedMessage()); } try { Object json = new JSONTokener(result).nextValue(); if (json instanceof JSONObject) { retVal.setParsedResponse((JSONObject) json); return (JSONObject) json; } } catch (JSONException e) { e.printStackTrace(); } // If we got this far, we got something very wrong... Log.e(TAG, "Didn't get a valid JSON response!"); return null; }
From source file:org.caratarse.auth.services.controller.UserAuthorizationControllerTest.java
@Test public void updateAuthorizationToUser() throws UnsupportedEncodingException, IOException { HttpPut putRequest = new HttpPut( BASE_URL + "/users/a1ab82a6-c8ce-4723-8532-777c4b05d03c/authorizations/ROLE_PRINTER.json"); StringEntity input = new StringEntity( "{\"permissions\":{ \"read\": true, \"write\": false, \"execute\": false}}"); input.setContentType("application/json"); putRequest.setEntity(input);/*ww w . j a v a2s . co m*/ HttpResponse response = httpClient.execute(putRequest); assertEquals(204, response.getStatusLine().getStatusCode()); HttpGet getRequest = new HttpGet( BASE_URL + "/users/a1ab82a6-c8ce-4723-8532-777c4b05d03c/authorizations/ROLE_PRINTER.json"); response = httpClient.execute(getRequest); assertEquals(200, response.getStatusLine().getStatusCode()); log.debug(IOUtils.toString(response.getEntity().getContent())); }
From source file:com.joken.notice.message.util.HttpRequestHandler.java
/** * ??post/*from ww w . j av a 2s .c om*/ * @Auther Hanzibin * @date 3:18:48 PM,Mar 11, 2016 * @return String */ public String sendPostRequest() { CloseableHttpResponse httpResponse = null; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(300); connManager.setDefaultMaxPerRoute(20); if (requestConfig == null) { requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000) .setStaleConnectionCheckEnabled(true).setConnectTimeout(10000).setSocketTimeout(10000).build(); } CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager) .setDefaultRequestConfig(requestConfig).build(); HttpPost hp = new HttpPost(url); try { StringEntity entity = new StringEntity(postData, Charset.forName("UTF-8"));//? entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); hp.setEntity(entity); httpResponse = httpClient.execute(hp); return EntityUtils.toString(httpResponse.getEntity()); } catch (Throwable t) { t.printStackTrace(); log.info("??Http" + postData.toString() + ""); } finally { try { hp.releaseConnection(); } catch (Exception e) { } } return null; }