List of usage examples for org.apache.http.client.methods HttpPost setEntity
public void setEntity(final HttpEntity entity)
From source file:att.jaxrs.client.Tag.java
public static long getExistingRecord(String tag_name) { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("tag_name", tag_name)); HttpResponse result;/*from w w w .ja va 2s . c o m*/ String resultStr; TagCollection tagCollection = new TagCollection(); try { System.out.println("invoking last added: " + tag_name); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(Constants.SELECT_LAST_ADDED_TAG_RESOURCE); post.setEntity(new UrlEncodedFormEntity(urlParameters)); result = httpClient.execute(post); System.out.println(Constants.RESPONSE_STATUS_CODE + result); resultStr = Util.getStringFromInputStream(result); tagCollection = Marshal.unmarshal(TagCollection.class, resultStr); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } if (null != tagCollection.getTag()) { return tagCollection.getTag()[0].getTag_id(); } return -1L; }
From source file:Main.java
public static HttpEntity getEntity(String uri, ArrayList<BasicNameValuePair> params, int method) throws ClientProtocolException, IOException { mClient = new DefaultHttpClient(); HttpUriRequest request = null;//from ww w . j a v a 2 s . c om switch (method) { case METHOD_GET: StringBuilder sb = new StringBuilder(uri); if (params != null && !params.isEmpty()) { sb.append("?"); for (BasicNameValuePair param : params) { sb.append(param.getName()).append("=").append(URLEncoder.encode(param.getValue(), "UTF_8")) .append("&"); } sb.deleteCharAt(sb.length() - 1); } request = new HttpGet(sb.toString()); break; case METHOD_POST: HttpPost post = new HttpPost(uri); if (params != null && !params.isEmpty()) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF_8"); post.setEntity(entity); } request = post; break; } mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); HttpResponse response = mClient.execute(request); System.err.println(response.getStatusLine().toString()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return response.getEntity(); } return null; }
From source file:edu.cmu.lti.oaqa.bioqa.providers.kb.TmToolConceptProvider.java
private static String submitText(String trigger, String text) throws IOException { CloseableHttpClient client = clientBuilder.build(); HttpPost post = new HttpPost(URL_PREFIX + trigger + "/Submit/"); post.setEntity(new StringEntity(text)); HttpResponse response = client.execute(post); String session = IOUtils.toString(response.getEntity().getContent()); HttpGet get = new HttpGet(URL_PREFIX + session + "/Receive/"); response = client.execute(get);/*from w w w. j av a 2 s.c o m*/ return IOUtils.toString(response.getEntity().getContent()); }
From source file:org.n52.oss.testdata.sml.GeneratorClient.java
/** * @param requestDoc//from w ww. j ava2 s . co m * @return * @throws UnsupportedEncodingException * @throws IOException * @throws HttpException */ private static XmlObject sendRequest(InsertSensorInfoRequestDocument requestDoc) throws UnsupportedEncodingException, IOException, HttpException { HttpPost request = new HttpPost(sirURL); request.setEntity(new StringEntity(requestDoc.xmlText(XmlTools.unconfiguredXmlOptionsForNamespaces()), STRING_REQUEST_ENCODING, STRING_REQUEST_CHARACTER_ENCODING)); // String host = System.getProperty(SYSTEM_PROPERTY_PROXY_HOST); // String port = System.getProperty(SYSTEM_PROPERTY_PROXY_PORT); // if (host != null && host.length() > 0 && port != null && port.length() > 0) { // int portNumber = Integer.parseInt(port); // HostConfiguration hostConfig = new HostConfiguration(); // hostConfig.setProxy(host, portNumber); // httpClient.setHostConfiguration(hostConfig); // } httpClient.execute(request); XmlObject response = null; try { response = XmlObject.Factory.parse(request.getEntity().getContent()); } catch (XmlException e) { log.error("Error parsing response.", e); return null; } return response; }
From source file:org.eclipse.lyo.testsuite.server.trsutils.SendUtil.java
/** * /* ww w.j a v a 2 s.c om*/ * @param uri resource uri for creation factory * @param httpClient client used to post to the uri * @param httpContext http context to use for the call * @param contentType content type to be used in the creation * @param content content to be used in the creation * @throws SendException if an error occurs in posting to the uri */ public static String createResource(String uri, HttpClient httpClient, HttpContext httpContext, String contentType, String content) throws SendException { String createdResourceUri = ""; if (uri == null) throw new IllegalArgumentException(Messages.getServerString("send.util.uri.null")); //$NON-NLS-1$ if (httpClient == null) throw new IllegalArgumentException(Messages.getServerString("send.util.httpclient.null")); //$NON-NLS-1$ try { new URL(uri); // Make sure URL is valid HttpPost post = new HttpPost(uri); StringEntity entity = new StringEntity(content); post.setEntity(entity); post.setHeader(HttpConstants.ACCEPT, HttpConstants.CT_APPLICATION_RDF_XML);//$NON-NLS-1$ post.addHeader(HttpConstants.CONTENT_TYPE, contentType); post.addHeader(HttpConstants.CACHE_CONTROL, "max-age=0"); //$NON-NLS-1$ HttpResponse resp = httpClient.execute(post); try { if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { HttpErrorHandler.responseToException(resp); } createdResourceUri = resp.getFirstHeader(HttpConstants.LOCATION).getValue(); HttpResponseUtil.finalize(resp); } finally { try { if (entity != null) { EntityUtils.consume(entity); } } catch (IOException e) { // ignore } } } catch (Exception e) { String uriLocation = Messages.getServerString("send.util.uri.unidentifiable"); //$NON-NLS-1$ if (uri != null && !uri.isEmpty()) { uriLocation = uri; } throw new SendException(MessageFormat.format(Messages.getServerString("send.util.retrieve.error"), //$NON-NLS-1$ uriLocation)); } return createdResourceUri; }
From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.RemoteDCRClient.java
public static OAuthApplicationInfo createOAuthApplication(RegistrationProfile registrationProfile, String host) throws DynamicClientRegistrationException { if (log.isDebugEnabled()) { log.debug("Invoking DCR service to create OAuth application for web app : " + registrationProfile.getClientName()); }// w w w . j av a2 s . co m DefaultHttpClient httpClient = getHTTPSClient(); String clientName = registrationProfile.getClientName(); try { URI uri = new URIBuilder().setScheme( DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL) .setHost(host) .setPath( DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) .build(); Gson gson = new Gson(); StringEntity entity = new StringEntity(gson.toJson(registrationProfile), DynamicClientWebAppRegistrationConstants.ContentTypes.CONTENT_TYPE_APPLICATION_JSON, DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8); HttpPost httpPost = new HttpPost(uri); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); HttpEntity responseData = response.getEntity(); String responseString = EntityUtils.toString(responseData, DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8); if (status != 201) { String msg = "Backend server error occurred while invoking DCR endpoint for " + "registering service-provider upon web-app : '" + clientName + "'; Server returned response '" + responseString + "' with HTTP status code '" + status + "'"; throw new DynamicClientRegistrationException(msg); } return getOAuthApplicationInfo(gson.fromJson(responseString, JsonElement.class)); } catch (URISyntaxException e) { throw new DynamicClientRegistrationException( "Exception occurred while constructing the URI for invoking " + "DCR endpoint for registering service-provider for web-app : " + clientName, e); } catch (UnsupportedEncodingException e) { throw new DynamicClientRegistrationException( "Exception occurred while constructing the payload for invoking " + "DCR endpoint for registering service-provider for web-app : " + clientName, e); } catch (IOException e) { throw new DynamicClientRegistrationException("Connection error occurred while invoking DCR endpoint for" + " registering service-provider for web-app : " + clientName, e); } finally { if (httpClient != null) { httpClient.close(); } } }
From source file:org.jboss.as.test.integration.domain.AbstractSSLMasterSlaveTestCase.java
private static ModelNode executeOverHttp(URI mgmtURI, String operation) throws IOException { CloseableHttpClient httpClient = createHttpClient(mgmtURI); HttpEntity operationEntity = new StringEntity(operation, ContentType.APPLICATION_JSON); HttpPost httpPost = new HttpPost(mgmtURI); httpPost.setEntity(operationEntity); HttpResponse response;//from w ww . j ava 2 s . c o m ModelNode responseNode; try { response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } responseNode = ModelNode.fromJSONStream(response.getEntity().getContent()); EntityUtils.consume(entity); } finally { httpClient.close(); } return responseNode; }
From source file:fr.julienvermet.bugdroid.util.NetworkUtils.java
public static NetworkResult postJson(String url, JSONObject data) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); int statusCode = 0; try {// w w w .jav a 2s .com StringEntity se = new StringEntity(data.toString()); httpPost.setEntity(se); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse response = client.execute(httpPost); StatusLine statusLine = response.getStatusLine(); statusCode = statusLine.getStatusCode(); // if (statusCode == 201) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); // } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } return new NetworkResult(statusCode, builder.toString()); }
From source file:org.thoughtcrime.securesms.mms.MmsSendHelper.java
private static byte[] makePost(MmsConnectionParameters parameters, byte[] mms) throws ClientProtocolException, IOException { Log.w("MmsSender", "Sending MMS1 of length: " + mms.length); try {// ww w . j av a2 s . c o m HttpClient client = constructHttpClient(parameters); URI hostUrl = new URI(parameters.getMmsc()); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); HttpPost request = new HttpPost(parameters.getMmsc()); ByteArrayEntity entity = new ByteArrayEntity(mms); entity.setContentType("application/vnd.wap.mms-message"); request.setEntity(entity); request.setParams(client.getParams()); request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic"); HttpResponse response = client.execute(target, request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase()); return parseResponse(response.getEntity()); } catch (URISyntaxException use) { Log.w("MmsDownlader", use); throw new IOException("Bad URI syntax"); } }
From source file:org.nuxeo.connect.registration.RegistrationHelper.java
public static String remoteRegisterInstance(String login, String password, String prjId, NuxeoClientInstanceType type, String description) { String url = getBaseUrl() + POST_REGISTER_SUFFIX; List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("projectId", prjId)); nvps.add(new BasicNameValuePair("description", description)); nvps.add(new BasicNameValuePair("type", type.getValue())); nvps.add(new BasicNameValuePair("CTID", TechnicalInstanceIdentifier.instance().getCTID())); HttpPost method = new HttpPost(url); try {//ww w . j ava 2 s . co m method.setEntity(new UrlEncodedFormEntity(nvps)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = httpClient.execute(method, getHttpClientContext(url, login, password))) { int rc = httpResponse.getStatusLine().getStatusCode(); if (rc == HttpStatus.SC_OK) { HttpEntity responseEntity = httpResponse.getEntity(); return responseEntity == null ? null : EntityUtils.toString(responseEntity); } else { log.error("Unhandled response code: " + rc); } } catch (IOException e) { throw new RuntimeException(e); } return null; }