List of usage examples for org.apache.http.client.methods HttpPost setEntity
public void setEntity(final HttpEntity entity)
From source file:org.neo4j.nlp.examples.author.main.java
private static String executePost(String targetURL, String payload) { try {/*from w w w . ja v a 2 s . co m*/ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(targetURL); StringEntity input = new StringEntity(payload); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); StringBuilder output = new StringBuilder(); while (br.read() != -1) { output.append(br.readLine()).append('\n'); } httpClient.getConnectionManager().shutdown(); return output.toString(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.oakhole.voa.utils.HttpClientUtils.java
/** * ??/*from w ww . j a v a 2 s .c o m*/ * * @param uri * @param params * @return */ public static String post(String uri, String params) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(uri); StringEntity stringEntity = new StringEntity(params, CHARSET.toString()); httpPost.setEntity(stringEntity); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { httpResponse.close(); return EntityUtils.toString(httpResponse.getEntity(), CHARSET); } } catch (IOException e) { logger.error(":{}", e.getMessage()); } return ""; }
From source file:topoos.APIAccess.APICaller.java
/** * Initiates an operation on topoos API. * /*from www.j a va 2 s .c om*/ * @param operation * Represents the operation to be executed * @param result * Represents a result returned from a query to API topoos * @throws IOException * @throws TopoosException */ public static void ExecuteOperation(APIOperation operation, APICallResult result, Integer service) throws IOException, TopoosException { HttpClient hc = new DefaultHttpClient(); if (!operation.ValidateParams()) throw new TopoosException(TopoosException.NOT_VALID_PARAMS); String OpURI = ""; switch (service) { case SERVICE_API: OpURI = GetURLAPItopoos() + operation.ConcatParams(); break; case SERVICE_PIC: OpURI = GetURLPICAPItopoos() + operation.ConcatParams(); break; case SERVICE_SOCIAL: OpURI = GetURLSOCIALAPItopoos() + operation.ConcatParams(); break; default: OpURI = GetURLAPItopoos() + operation.ConcatParams(); break; } if (Constants.DEBUGURL) { Log.d(Constants.TAG, OpURI); // appendLog(OpURI); } HttpPost post = new HttpPost(OpURI); // POST if (operation.getMethod().equals("POST")) { post.setEntity(operation.BodyParams()); } HttpResponse rp = hc.execute(post); HttpParams httpParams = hc.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, Constants.HTTP_WAITING_MILISECONDS); HttpConnectionParams.setSoTimeout(httpParams, Constants.HTTP_WAITING_MILISECONDS); if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result.setResult(EntityUtils.toString(rp.getEntity())); if (Constants.DEBUGURL) { Log.d(Constants.TAG, result.getResult()); // appendLog(result.getResult()); } result.setError(null); result.setParameters(); } else { switch (rp.getStatusLine().getStatusCode()) { case 400: throw new TopoosException(TopoosException.ERROR400); case 405: throw new TopoosException(TopoosException.ERROR405); default: throw new TopoosException("Error: " + rp.getStatusLine().getStatusCode() + ""); } } }
From source file:com.google.resting.rest.client.BaseRESTClient.java
protected static HttpRequest buildHttpRequest(ServiceContext serviceContext) { String path = serviceContext.getPath(); Verb verb = serviceContext.getVerb(); HttpEntity httpEntity = serviceContext.getHttpEntity(); List<Header> headers = serviceContext.getHeaders(); if (verb == Verb.GET) { HttpGet httpGet = new HttpGet(path); if (headers != null) { for (Header header : headers) httpGet.addHeader(header); }// w w w . j av a2 s . c om return httpGet; } else if (verb == Verb.POST) { HttpPost httpPost = new HttpPost(path); if (headers != null) { for (Header header : headers) httpPost.addHeader(header); } if (httpEntity != null) httpPost.setEntity(httpEntity); return httpPost; } else if (verb == Verb.DELETE) { HttpDelete httpDelete = new HttpDelete(path); if (headers != null) { for (Header header : headers) httpDelete.addHeader(header); } return httpDelete; } else { HttpPut httpPut = new HttpPut(path); if (headers != null) { for (Header header : headers) httpPut.addHeader(header); } if (httpEntity != null) httpPut.setEntity(httpEntity); return httpPut; } //if }
From source file:it.sasabz.android.sasabus.classes.hafas.XMLRequest.java
/** * Sends a HTTP-Post request to the xml-interface of the hafas travelplanner * @param xml is the xml-file containing a xml-request for the hafas travelplanner * @return the response of the hafas travelplanner xml interface */// w ww. j a v a2 s . com private static String execute(String xml) { String ret = ""; if (!haveNetworkConnection()) { return ret; } try { HttpClient http = new DefaultHttpClient(); HttpPost post = new HttpPost(SASAbus.getContext().getString(R.string.xml_server)); StringEntity se = new StringEntity(xml, HTTP.UTF_8); se.setContentType("text/xml"); post.setEntity(se); HttpResponse response = http.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { ret = EntityUtils.toString(response.getEntity()); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; }
From source file:att.jaxrs.client.Library.java
public static Library selectWithKeyLibraryResource(long content_id) { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("content_id", Long.toString(content_id))); LibraryCollection libraryCollection = new LibraryCollection(); try {/*from w w w.j a v a 2 s .c o m*/ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(Constants.SELECT_WITH_KEY_LIBRARY_RESOURCE); post.setEntity(new UrlEncodedFormEntity(urlParameters)); HttpResponse result = httpClient.execute(post); System.out.println(Constants.RESPONSE_STATUS_CODE + result); String resultStr = Util.getStringFromInputStream(result); System.out.println(Constants.RESPONSE_BODY + resultStr); System.out.println("##################################"); libraryCollection = Marshal.unmarshal(LibraryCollection.class, resultStr); } catch (Exception e) { System.out.println(e.getMessage()); } if (libraryCollection.getLibrary().length == 1) { return libraryCollection.getLibrary()[0]; } return null; }
From source file:com.wms.opensource.images3android.images3.ImageS3Service.java
public static int addImage(String baseUrl, String imagePlantId, String filePath) { File file = new File(filePath); try {/*from w w w . j a v a2 s. com*/ HttpClient client = getClient(); String url = baseUrl + imagePlantId + "/images"; HttpPost httppost = new HttpPost(url); InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httppost.setEntity(reqEntity); HttpResponse response = client.execute(httppost); return response.getStatusLine().getStatusCode(); } catch (Exception e) { return -1; } }
From source file:co.cask.cdap.gateway.handlers.metrics.MetricsQueryTest.java
private static void testSingleMetricWithPost(String resource, int value) throws Exception { HttpPost post = getPost("/v2/metrics"); post.setHeader("Content-type", "application/json"); post.setEntity(new StringEntity("[\"" + resource + "\"]")); HttpResponse response = doPost(post); Assert.assertEquals("POST " + resource + " did not return 200 status.", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); String content = new String(ByteStreams.toByteArray(response.getEntity().getContent()), Charsets.UTF_8); JsonArray json = new Gson().fromJson(content, JsonArray.class); // Expected result looks like // [/*from w w w . j a v a 2 s .c o m*/ // { // "path":"/smth/smth", // "result":{"data":<value>} // } // ] Assert.assertEquals("POST " + resource + " returned unexpected results.", value, json.get(0).getAsJsonObject().getAsJsonObject("result").get("data").getAsInt()); }
From source file:core.HttpClient.java
/** * gets the checksum of the updated file * //from w w w. ja va 2s . c o m * @return String- the checksum */ public static String getUpdateFileChecksum() { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response; HttpEntity entity; HttpPost httpost = new HttpPost(COMPANY_WEBSITE); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("checksum", "")); httpost.setEntity(new UrlEncodedFormEntity(nvps)); response = httpclient.execute(httpost); entity = response.getEntity(); String data = "", line; BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); while ((line = br.readLine()) != null) { data += line; } if (data.equals("")) { return null; } else { return data; } } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:io.openkit.OKHTTPClient.java
public static void postJSON(String relativeUrl, JSONObject requestParams, AsyncHttpResponseHandler responseHandler) { StringEntity sEntity = getJSONString(requestParams); HttpPost request = new HttpPost(getAbsoluteUrl(relativeUrl)); if (sEntity == null) { responseHandler.onFailure(new Throwable("JSON encoding error"), "JSON encoding error"); } else {// ww w .j a v a 2s .c om request.setEntity(sEntity); sign(request); client.post(request, "application/json", responseHandler); } }