List of usage examples for org.apache.http.client.methods HttpPost setEntity
public void setEntity(final HttpEntity entity)
From source file:Main.java
/** * Method to initialize and prepare an HttpPost object * @param file/*w w w . j a v a2s . co m*/ * @param url * @param chunked * @return HttpPost */ public static HttpPost prepareRequest(File file, String url, boolean chunked) { HttpPost post = new HttpPost(url); FileEntity reqEntity = new FileEntity(file, "binary/octet-stream"); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(chunked); post.setEntity(reqEntity); return post; }
From source file:me.ixfan.wechatkit.util.HttpClientUtil.java
/** * POST data using the Content-Type <code>multipart/form-data</code>. * This enables uploading of binary files etc. * * @param url URL of request.//from w w w .ja va2 s . co m * @param textInputs Name-Value pairs of text inputs. * @param binaryInputs Name-Value pairs of binary files inputs. * @return JSON object of response. * @throws IOException If I/O error occurs. */ public static JsonObject sendMultipartRequestAndGetJsonResponse(String url, Map<String, String> textInputs, Map<String, MultipartInput> binaryInputs) throws IOException { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); if (null != textInputs) { textInputs.forEach((k, v) -> multipartEntityBuilder.addTextBody(k, v)); } if (null != binaryInputs) { binaryInputs.forEach((k, v) -> { if (null == v.getDataBytes()) { multipartEntityBuilder.addBinaryBody(k, v.getFile(), v.getContentType(), v.getFile().getName()); } else { multipartEntityBuilder.addBinaryBody(k, v.getDataBytes(), v.getContentType(), v.getFilename()); } }); } CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setEntity(multipartEntityBuilder.build()); return httpClient.execute(post, new JsonResponseHandler()); }
From source file:info.bonjean.beluga.util.HTTPUtil.java
private static String jsonRequest(String urlStr, String data) throws CommunicationException { try {// www.j a v a 2 s.com StringEntity json = new StringEntity(data.toString()); json.setContentType("application/json"); HttpPost post = new HttpPost(urlStr); post.addHeader("Content-Type", "application/json"); post.setEntity(json); return BelugaHTTPClient.getInstance().requestPost(post); } catch (Exception e) { throw new CommunicationException("communicationProblem", e); } }
From source file:jp.co.conit.sss.sp.ex1.util.HttpUtil.java
/** * POST??????//www . j a v a 2s . c o m * * @param url API?URL * @param httpEntity ? * @return */ public static String post(String url, UrlEncodedFormEntity httpEntity) throws Exception { if (url == null) { throw new IllegalArgumentException("'url' must not be null."); } if (httpEntity == null) { throw new IllegalArgumentException("'httpEntity' must not be null."); } String result = null; DefaultHttpClient httpclient = new DefaultHttpClient(getHttpParam()); HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(httpEntity); HttpResponse response = httpclient.execute(httpPost); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); response.getEntity().writeTo(byteArrayOutputStream); result = byteArrayOutputStream.toString(); } catch (ClientProtocolException e) { throw new Exception(); } catch (IllegalStateException e) { throw new Exception(); } catch (IOException e) { throw new Exception(); } return result; }
From source file:Main.java
public static String postReqAsJson(String uri, String requestJson) throws ClientProtocolException, IOException { Log.i(TAG, "Send data to :" + uri + " ========== and the data str:" + requestJson); HttpPost post = new HttpPost(uri); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("attendanceClientJSON", requestJson)); post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String retStr = EntityUtils.toString(response.getEntity()); Log.i(TAG, "=================response str:" + retStr); return retStr; }/*from w w w. j a va 2 s . com*/ return response.getStatusLine().getStatusCode() + "ERROR"; }
From source file:org.n52.sor.client.Client.java
/** * @param request//w ww .j a v a 2s .c o m * @return * @throws UnsupportedEncodingException * @throws IOException * @throws HttpException */ private static XmlObject doSend(String request, String requestMethod) throws UnsupportedEncodingException, IOException { log.debug("Sending request (first 100 characters): {}", request.substring(0, Math.min(request.length(), 100))); PropertiesManager pm = PropertiesManager.getInstance(); // create and set up HttpClient try (CloseableHttpClient client = HttpClientBuilder.create().build();) { HttpRequestBase method = null; if (requestMethod.equals(GET_METHOD)) { String sorURL = pm.getServiceEndpointGet(); log.debug("Client connecting via GET to {}", sorURL); HttpGet get = new HttpGet(request); method = get; } else if (requestMethod.equals(POST_METHOD)) { String sorURL = pm.getServiceEndpointPost(); log.debug("Client connecting via POST to {}", sorURL); HttpPost postMethod = new HttpPost(sorURL.toString()); postMethod.setEntity( new StringEntity(request, PropertiesManager.getInstance().getClientRequestContentType())); method = postMethod; } else throw new IllegalArgumentException("requestMethod not supported!"); HttpResponse httpResponse = client.execute(method); XmlObject response = XmlObject.Factory.parse(httpResponse.getEntity().getContent()); return response; } catch (XmlException e) { log.error("Error parsing response.", e); } return null; }
From source file:edu.illinois.whereru.HTTPRequest.java
public static JSONObject makeHttpRequest(String urlString, String method, List<NameValuePair> params) { JSONObject jsonObject = null;/*from ww w. jav a 2s . com*/ try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse; if (method.equals("POST")) { // init post HttpPost httpPost = new HttpPost(urlString); // set the resource to send httpPost.setEntity(new UrlEncodedFormEntity(params)); // send the request, retrieve response httpResponse = httpClient.execute(httpPost); } else { // GET method // formulate url String paramString = URLEncodedUtils.format(params, "utf-8"); urlString += "?" + paramString; // init GET HttpGet httpGet = new HttpGet(urlString); // send the request, retrieve response httpResponse = httpClient.execute(httpGet); } // retrieve content from the response HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); jsonObject = new JSONObject(sb.toString()); } catch (NullPointerException e) { } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonObject; }
From source file:org.epics.archiverappliance.retrieval.channelarchiver.XMLRPCClient.java
/** * Internal method to make a XML_RPC post call and call the SAX handler on the returned document. * @param serverURL The Server URL// ww w. java 2 s . co m * @param handler DefaultHandler * @param postEntity StringEntity * @throws IOException   * @throws SAXException   */ private static void doHTTPPostAndCallSAXHandler(String serverURL, DefaultHandler handler, StringEntity postEntity) throws IOException, SAXException { logger.debug("Executing doHTTPPostAndCallSAXHandler with the server URL " + serverURL); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(serverURL); postMethod.addHeader("Content-Type", "text/xml"); postMethod.setEntity(postEntity); logger.debug("Executing the HTTP POST" + serverURL); HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); try (InputStream is = entity.getContent()) { SAXParserFactory sfac = SAXParserFactory.newInstance(); sfac.setNamespaceAware(false); sfac.setValidating(false); SAXParser parser = sfac.newSAXParser(); parser.parse(is, handler); } catch (ParserConfigurationException pex) { throw new IOException(pex); } } else { throw new IOException("HTTP response did not have an entity associated with it"); } }
From source file:com.android.isoma.enc.ServerCommunicator.java
public static String executePost(ArrayList<NameValuePair> postParameters) { String ServerResponse = null; HttpClient httpClient = getHttpClient(); ResponseHandler<String> response = new BasicResponseHandler(); HttpPost request = new HttpPost(url); try {// w ww.jav a 2 s. c o m request.setHeader("Content-Type", "application/x-www-form-urlencoded"); request.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8)); ServerResponse = httpClient.execute(request, response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ServerResponse; }
From source file:net.giovannicapuano.galax.util.Utils.java
/** * Perform a HTTP POST request.// w ww. j a va2 s . c o m */ public static HttpData postData(String path, List<NameValuePair> post, Context context) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 10000); int status = HttpStatus.SC_INTERNAL_SERVER_ERROR; String body = ""; HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, new PersistentCookieStore(context)); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build()); try { HttpPost httpPost = new HttpPost(context.getString(R.string.server) + path); httpPost.setEntity(new UrlEncodedFormEntity(post)); HttpResponse response = httpClient.execute(httpPost, localContext); status = response.getStatusLine().getStatusCode(); body = EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return new HttpData(status, body); }