List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:org.structr.android.restclient.StructrObject.java
private static int create(String path, StructrObject entity, Type type) throws Throwable { AndroidHttpClient httpClient = getHttpClient(); HttpPost httpPost = new HttpPost(path); HttpResponse response = null;// www . j a v a 2s . c o m Throwable throwable = null; int responseCode = 0; try { StringBuilder buf = new StringBuilder(); gson.toJson(entity, type, buf); StringEntity body = new StringEntity(buf.toString(), "UTF-8"); body.setContentType("application/json"); httpPost.setEntity(body); configureRequest(httpPost); response = httpClient.execute(httpPost); responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 201) { String location = response.getFirstHeader("Location").getValue(); String newId = getIdFromLocation(location); // only set ID of it's not already set if (entity.getId() == null) { entity.setId(newId); } } else { throw new StructrException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } catch (Throwable t) { throwable = t; } finally { if (response != null) { response.getEntity().consumeContent(); } } if (throwable != null) { throw throwable; } return responseCode; }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
public static String postXmlRequest(String url, StringEntity stringEntity) throws IOException { HttpParams httpParameters = HttpHelpers.getConnectionParameters(); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); HttpHelpers.addCommonHeaders(httpPost); stringEntity.setContentType("text/xml"); httpPost.setEntity(stringEntity);/*from w ww . jav a 2 s . co m*/ return getUncompressedResponseString(httpClient.execute(httpPost)); }
From source file:com.msopentech.applicationgateway.connection.Router.java
/** * Performs HTTP POST request and obtains session ID. * //w ww . j a va 2 s .co m * @param traits Connection traits. * @param agentIdJSON Selected proxy agent ID (in JSON string format) that will be used to route through all the requests. * * @return Session ID. Returns <code>null</code> if exception is caught. Always provides error description if error occurs. */ private static String obtainSession(ConnectionTraits traits, String agentIdJSON) { try { if (traits == null || TextUtils.isEmpty(traits.token)) { String errorText = String.format(ERROR_SESSION, "Traits argument is null or does not contain valid token."); if (traits != null) { traits.setError(errorText); } else { traits = new ConnectionTraits(errorText); } return null; } HttpClient sessionClient = new DefaultHttpClient(); HttpPost sessionRequest = new HttpPost( EnterpriseBrowserActivity.CLOUD_CONNECTION_HOST_PREFIX + "user/session"); sessionRequest.addHeader("x-bhut-authN-token", traits.token); StringEntity requestBody = null; requestBody = new StringEntity(agentIdJSON); requestBody.setContentType("application/json"); sessionRequest.setEntity(requestBody); BasicHttpResponse response = null; response = (BasicHttpResponse) sessionClient.execute(sessionRequest); HttpEntity responseEntity = response.getEntity(); InputStream responseStream = null; String result = null; responseStream = responseEntity.getContent(); BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream)); String line; StringBuffer actualResponse = new StringBuffer(); while ((line = responseReader.readLine()) != null) { actualResponse.append(line); actualResponse.append('\r'); } result = actualResponse.toString(); JSONObject session = null; session = new JSONObject(result); result = session.getString(JSON_SESSION_ID_KEY); if (TextUtils.isEmpty(result)) { traits.setError(String.format(ERROR_SESSION, "Session is null or empty.")); } else { traits.setSession(result); return result; } } catch (final Exception e) { logError(e, Router.class.getSimpleName() + ".obtainSession() Failed"); traits.setError(String.format(ERROR_SESSION, "Session retrieval failed.")); } return null; }
From source file:com.msopentech.applicationgateway.connection.Router.java
/** * Performs HTTP POST request and obtains authentication token. * /*from w ww .ja va 2 s . co m*/ * @param credentials Authentication credentials * * @return {@link ConnectionTraits} with valid token OR with an error message if exception is caught or token retrieval failed or * token is <code>null</code> or an empty string. Does NOT return <code>null</code>. */ private static ConnectionTraits obtainToken(Credentials credentials) { ConnectionTraits connection = new ConnectionTraits(); try { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost("https://login.microsoftonline.com/extSTS.srf"); request.addHeader("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"); request.addHeader("Content-Type", "application/soap+xml; charset=utf-8"); Date now = new Date(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssZ"); String nowAsString = df.format(now); Calendar calendar = Calendar.getInstance(); calendar.setTime(now); calendar.add(Calendar.SECOND, 10 * 60); Date expires = calendar.getTime(); String expirationAsString = df.format(expires); String message = requestTemplate; message = message.replace("#{user}", credentials.getUsername()); message = message.replace("#{pass}", credentials.getPassword()); message = message.replace("#{created}", nowAsString); message = message.replace("#{expires}", expirationAsString); message = message.replace("#{resource}", "appgportal.cloudapp.net"); StringEntity requestBody = new StringEntity(message, HTTP.UTF_8); requestBody.setContentType("text/xml"); request.setEntity(requestBody); BasicHttpResponse response = null; response = (BasicHttpResponse) client.execute(request); HttpEntity entity = response.getEntity(); InputStream inputStream = null; String token = null; inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuffer actualResponse = new StringBuffer(); while ((line = reader.readLine()) != null) { actualResponse.append(line); actualResponse.append('\r'); } token = actualResponse.toString(); String start = "<wst:RequestedSecurityToken>"; int index = token.indexOf(start); if (-1 == index) { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); InputStream errorInputStream = new ByteArrayInputStream(token.getBytes()); Document currentDoc = documentBuilder.parse(errorInputStream); if (currentDoc == null) { return null; } String errorReason = null; String errorExplained = null; Node rootNode = null; if ((rootNode = currentDoc.getFirstChild()) != null && /* <S:Envelope> */ (rootNode = XmlUtility.getChildNode(rootNode, "S:Body")) != null && (rootNode = XmlUtility.getChildNode(rootNode, "S:Fault")) != null) { Node node = null; if ((node = XmlUtility.getChildNode(rootNode, "S:Reason")) != null) { errorReason = XmlUtility.getChildNodeValue(node, "S:Text"); } if ((node = XmlUtility.getChildNode(rootNode, "S:Detail")) != null && (node = XmlUtility.getChildNode(node, "psf:error")) != null && (node = XmlUtility.getChildNode(node, "psf:internalerror")) != null) { errorExplained = XmlUtility.getChildNodeValue(node, "psf:text"); } } if (!TextUtils.isEmpty(errorReason) && !TextUtils.isEmpty(errorExplained)) { logError(null, Router.class.getSimpleName() + ".obtainToken(): " + errorReason + " - " + errorExplained); connection.setError(String.format(ERROR_TOKEN, errorReason + ": " + errorExplained)); return connection; } } else { token = token.substring(index); String end = "</wst:RequestedSecurityToken>"; index = token.indexOf(end) + end.length(); token = token.substring(0, index); if (!TextUtils.isEmpty(token)) { connection.setToken(token); return connection; } } } catch (final Exception e) { logError(e, Router.class.getSimpleName() + ".obtainToken() Failed"); return connection.setError(String.format(ERROR_TOKEN, "Token retrieval failed with exception.")); } return connection.setError(String.format(ERROR_TOKEN, "Token retrieval failed.")); }
From source file:org.grameenfoundation.videointeractive.utils.HttpHelpers.java
public static InputStream postDataRequestAndGetStream(String url, StringEntity stringEntity, String contentType, int networkTimeout) throws IllegalStateException, ClientProtocolException, IOException { HttpParams httpParameters = HttpHelpers.getConnectionParameters(networkTimeout); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); HttpHelpers.addCommonHeaders(httpPost); stringEntity.setContentType(contentType); httpPost.setEntity(stringEntity);// w w w . j a v a 2s .c om return getInputStream(httpClient.execute(httpPost)); }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
public static InputStream postDataRequestAndGetStream(String url, StringEntity stringEntity, String contentType) throws IllegalStateException, ClientProtocolException, IOException { HttpParams httpParameters = HttpHelpers.getConnectionParameters(); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); HttpHelpers.addCommonHeaders(httpPost); stringEntity.setContentType(contentType); httpPost.setEntity(stringEntity);/*from w ww.ja va2 s . c o m*/ return getInputStream(httpClient.execute(httpPost)); }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
public static InputStream postDataRequestAndGetStream(String url, StringEntity stringEntity, String contentType, int networkTimeout) throws IllegalStateException, ClientProtocolException, IOException { HttpParams httpParameters = HttpHelpers.getConnectionParameters(networkTimeout); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); HttpHelpers.addCommonHeaders(httpPost); stringEntity.setContentType(contentType); httpPost.setEntity(stringEntity);//from w ww . j a v a 2s . c o m httpPost.addHeader("Accept-Encoding", "gzip"); return getInputStream(httpClient.execute(httpPost)); }
From source file:com.lostad.app.base.util.RequestUtil.java
public static String postRequest(final String url, final StringEntity params, String token, final boolean isSingleton) throws Exception { String json = null;//from www .j a v a 2 s .c o m HttpClient client = HttpClientManager.getHttpClient(isSingleton); HttpEntity resEntity = null; HttpPost post = new HttpPost(url); if (Validator.isNotEmpty(token)) { post.addHeader("token", token); } try { //long t1 = System.currentTimeMillis(); if (params != null) { params.setContentEncoding(HTTP.UTF_8); params.setContentType("application/x-www-form-urlencoded"); post.setEntity(params); } HttpResponse response = client.execute(post, new BasicHttpContext()); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200 //? json = EntityUtils.toString(resEntity); } } catch (Exception e) { if (post != null) { post.abort(); } throw e; } finally { if (resEntity != null) { try { resEntity.consumeContent(); } catch (IOException e) { e.printStackTrace(); } } client.getConnectionManager().closeExpiredConnections(); } return json; }
From source file:com.vmware.vchs.api.samples.services.Compute.java
/** * This method will use the provided input parameters to create a VM. * /* ww w. j av a 2s.com*/ * @param vdc * the VdcType instance to create the VM in to * @param template * the vApp template to create the VM from * @param vAppName * the name of the created VM * @param version * the version of the API to use * @param token * the OAUTH2 authentication token from IAM * @return an instance of VAppType if successful, null otherwise */ public static final VAppType createVmFromTemplate(VdcType vdc, VAppTemplateType template, String vAppName, String version, String token) { ReferenceType vappReference = new ReferenceType(); vappReference.setHref(template.getHref()); // Create an InstantiateVAppTemplateParamsType object and initialize it InstantiateVAppTemplateParamsType instvApp = new InstantiateVAppTemplateParamsType(); // Set the name of vApp using the options.vappname (command line option --targetvappname) instvApp.setName(vAppName); // Deploy the VM instvApp.setDeploy(Boolean.TRUE); // Power on this VM instvApp.setPowerOn(Boolean.TRUE); // vApp reference to be used instvApp.setSource(vappReference); instvApp.setDescription("VM Create from template"); instvApp.setAllEULAsAccepted(Boolean.TRUE); InstantiationParamsType instParams = new InstantiationParamsType(); instvApp.setInstantiationParams(instParams); // Get the HREF link to send POST to to instantiate the vapp List<LinkType> links = vdc.getLink(); String instantiateHref = null; for (LinkType link : links) { if (link.getType().contains("instantiateVAppTemplate")) { instantiateHref = link.getHref(); break; } } // Create HttpPost request to perform InstantiatevApp action HttpPost post = new HttpPost(instantiateHref); post.setHeader(HttpHeaders.CONTENT_TYPE, SampleConstants.APPLICATION_PLUS_XML_VERSION + version); post.setHeader(HttpHeaders.ACCEPT, SampleConstants.APPLICATION_PLUS_XML_VERSION + version + ";charset=utf-8"); post.setHeader(SampleConstants.VCD_AUTHORIZATION_HEADER, token); // Create the XSD generated ObjectFactory factory class ObjectFactory obj = new ObjectFactory(); // Create the InstantiateVdcTemplateParamsType from the ObjectFactory JAXBElement<InstantiateVAppTemplateParamsType> instvAppTemplate = obj .createInstantiateVAppTemplateParams(instvApp); // Get the StringEntity marshaled instance StringEntity se = HttpUtils.marshal(InstantiateVAppTemplateParamsType.class, instvAppTemplate); // Set the Content-Type header for the VM vApp template parameters se.setContentType("application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml"); post.setEntity(se); // Invoke the HttoPost to initiate the VM creation process HttpResponse response = HttpUtils.httpInvoke(post); // Make sure response status is 201 Created if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { return HttpUtils.unmarshal(response.getEntity(), VAppType.class); } return null; }
From source file:android.webkit.cts.CtsTestServer.java
/** * Create a string entity for the given content. *///from w ww . j a va 2 s.co m private static StringEntity createEntity(String content) { try { StringEntity entity = new StringEntity(content); entity.setContentType("text/html"); return entity; } catch (UnsupportedEncodingException e) { Log.w(TAG, e); } return null; }