List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:org.apache.tika.parser.recognition.tf.TensorflowRESTRecogniser.java
@Override public List<RecognisedObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { List<RecognisedObject> recObjs = new ArrayList<>(); try {//from ww w .j a va 2s . c om DefaultHttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(getApiUri(metadata)); try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) { //TODO: convert this to stream, this might cause OOM issue // InputStreamEntity is not working // request.setEntity(new InputStreamEntity(stream, -1)); IOUtils.copy(stream, byteStream); request.setEntity(new ByteArrayEntity(byteStream.toByteArray())); } HttpResponse response = client.execute(request); try (InputStream reply = response.getEntity().getContent()) { String replyMessage = IOUtils.toString(reply); if (response.getStatusLine().getStatusCode() == 200) { JSONObject jReply = new JSONObject(replyMessage); JSONArray jClasses = jReply.getJSONArray("classnames"); JSONArray jConfidence = jReply.getJSONArray("confidence"); if (jClasses.length() != jConfidence.length()) { LOG.warn("Classes of size {} is not equal to confidence of size {}", jClasses.length(), jConfidence.length()); } assert jClasses.length() == jConfidence.length(); for (int i = 0; i < jClasses.length(); i++) { RecognisedObject recObj = new RecognisedObject(jClasses.getString(i), LABEL_LANG, jClasses.getString(i), jConfidence.getDouble(i)); recObjs.add(recObj); } } else { LOG.warn("Status = {}", response.getStatusLine()); LOG.warn("Response = {}", replyMessage); } } } catch (Exception e) { LOG.warn(e.getMessage(), e); } LOG.debug("Num Objects found {}", recObjs.size()); return recObjs; }
From source file:ai.eve.volley.stack.HttpClientStack.java
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { byte[] body = null;//request.getBody(); if (body != null) { HttpEntity entity = new ByteArrayEntity(body); httpRequest.setEntity(entity);/*from w w w. ja v a 2s . c om*/ } }
From source file:org.brunocvcunha.instagram4j.requests.InstagramDirectShareRequest.java
@Override public StatusResult execute() throws ClientProtocolException, IOException { String recipients = ""; if (this.recipients != null) { recipients = "\"" + String.join("\",\"", this.recipients.toArray(new String[0])) + "\""; }//from w w w. j av a 2 s .c o m List<Map<String, String>> data = new ArrayList<Map<String, String>>(); Map<String, String> map = new HashMap<String, String>(); if (shareType == ShareType.MEDIA) { map.put("type", "form-data"); map.put("name", "media_id"); map.put("data", mediaId); data.add(map); } map = map.size() > 0 ? new HashMap<String, String>() : map; map.put("type", "form-data"); map.put("name", "recipient_users"); map.put("data", "[[" + recipients + "]]"); data.add(map); map = new HashMap<String, String>(); map.put("type", "form-data"); map.put("name", "client_context"); map.put("data", InstagramGenericUtil.generateUuid(true)); data.add(map); map = new HashMap<String, String>(); map.put("type", "form-data"); map.put("name", "thread_ids"); map.put("data", "[" + (threadId != null ? threadId : "") + "]"); data.add(map); map = new HashMap<String, String>(); map.put("type", "form-data"); map.put("name", "text"); map.put("data", message == null ? "" : message); data.add(map); HttpPost post = createHttpRequest(); post.setEntity(new ByteArrayEntity(buildBody(data, api.getUuid()).getBytes(StandardCharsets.UTF_8))); try (CloseableHttpResponse response = api.getClient().execute(post)) { api.setLastResponse(response); int resultCode = response.getStatusLine().getStatusCode(); String content = EntityUtils.toString(response.getEntity()); log.info("Direct-share request result: " + resultCode + ", " + content); post.releaseConnection(); StatusResult result = parseResult(resultCode, content); return result; } }
From source file:com.cloudera.livy.client.http.LivyConnection.java
synchronized <V> V post(Object body, Class<V> retType, String uri, Object... uriParams) throws Exception { HttpPost post = new HttpPost(); byte[] bodyBytes = mapper.writeValueAsBytes(body); post.setEntity(new ByteArrayEntity(bodyBytes)); return sendJSONRequest(post, retType, uri, uriParams); }
From source file:com.image32.demo.simpleapi.ContentHandler.java
@Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { HttpSession session = request.getSession(); response.setStatus(HttpServletResponse.SC_OK); httpHeaderNoCache(response);/*from w w w .ja v a 2s .c om*/ ((Request) request).setHandled(true); if (request.getMethod().equals("POST") && target.equals("/login")) { response.setContentType("application/json;charset=utf-8"); String requestToken = request.getParameter("requestToken"); String demoPass = request.getParameter("demoPass"); logger.info("logging in with requestToken:" + requestToken + " demoPass:" + demoPass); Image32APIAuthResponse responseObj = null; HashMap<String, String> out = new HashMap<String, String>(); if (demoPass != null && (demoPass.equals("admin"))) { //has no security for this demo. session.setAttribute("adminRole", true); //authenticate with image32 api DefaultHttpClient httpclient = new DefaultHttpClient();// HttpPost httpPost = new HttpPost(SimpleApiDemo.image32ApiAuthUrl); try { String body = "{\"client_id\": \"" + SimpleApiDemo.image32ApiClientId + "\",\"client_secret\":\"" + SimpleApiDemo.image32ApiSecrect + "\",\"auth_request_token\":\"" + requestToken + "\","; body += "\"scopes\":["; body += "{\"type\":\"user-id\",\"id\":\"abc_user_001\",\"permission\":\"view\"},"; //give access to all studies body += "{\"type\":\"case-id\",\"id\":\"abc\",\"permission\":\"full\"}"; //give full access to case/folder 'abc' body += "]}"; HttpEntity entity = new ByteArrayEntity(body.getBytes("UTF-8")); httpPost.setEntity(entity); HttpResponse apiResponse = httpclient.execute(httpPost); String result = EntityUtils.toString(apiResponse.getEntity()); logger.info("image32 api response:" + result); EntityUtils.consume(entity); //parse response Gson gson = new Gson(); responseObj = gson.fromJson(result, Image32APIAuthResponse.class); session.setAttribute("responseObj", responseObj); if (responseObj != null && responseObj.getRedirect_url() != null) { out.put("confirmUrl", responseObj.getRedirect_url()); } } catch (ParseException e) { logger.warn(e.getMessage()); } finally { httpPost.releaseConnection(); } out.put("result", "true"); //print journal entries Gson gson = new Gson(); //print response String outStr = gson.toJson(out); response.getWriter().println(outStr); } else { response.getWriter().println("{\"result\":false}");//role is not valid } return; } // else if (request.getMethod().equals("POST") && target.equals("/getStudies") && isWriter(session)) { // //get all available studies for current session // response.setContentType("application/json;charset=utf-8"); // logger.info("getStudies"); // // Image32APIAuthResponse responseObj = (Image32APIAuthResponse)session.getAttribute("responseObj"); // if(responseObj!=null){ // //get all studies // HttpGet httpGet = new HttpGet(SimpleApiDemo.image32ApiGetStudiesUrl); // // try { // httpGet.setHeader("Authorization", "Bearer "+responseObj.getAccess_token()); // DefaultHttpClient httpclient = new DefaultHttpClient(); // HttpResponse apiResponse = httpclient.execute(httpGet); // String result = EntityUtils.toString(apiResponse.getEntity()); // EntityUtils.consume(apiResponse.getEntity()); // response.getWriter().println(result); // logger.info("image32 api response:" + result); // // } catch (ParseException e) { // logger.warn(e.getMessage()); // // }finally{ // httpGet.releaseConnection(); // } // } // } }
From source file:com.couchbase.capi.TestCAPI.java
public void testRevsDiff() throws Exception { HttpClient client = getClient();//w ww . j a v a2 s . com HttpPost request = new HttpPost(String.format("http://localhost:%d/default/_revs_diff", port)); List<String> revs = new ArrayList<String>(); revs.add("1-abc"); revs.add("2-def"); Map<String, Object> revsDiff = new HashMap<String, Object>(); revsDiff.put("12345", revs); request.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(revsDiff))); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); Map<String, Map<String, List<Object>>> details = null; if (entity != null) { InputStream input = entity.getContent(); try { details = mapper.readValue(input, Map.class); } finally { input.close(); } } Assert.assertTrue(details.containsKey("12345")); Assert.assertTrue(details.get("12345").containsKey("missing")); Assert.assertEquals(2, details.get("12345").get("missing").size()); Assert.assertTrue(details.get("12345").get("missing").contains("1-abc")); Assert.assertTrue(details.get("12345").get("missing").contains("2-def")); }
From source file:info.androidhive.volleyjson.util.SslHttpStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *///w w w.j av a 2 s .c o m @SuppressWarnings("deprecation") /* protected */ static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); //setMultiPartBody(postRequest,request); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); //setMultiPartBody(putRequest,request); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } // Added in source code of Volley libray. case Method.PATCH: { HttpPatch patchRequest = new HttpPatch(request.getUrl()); patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(patchRequest, request); return patchRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:com.nxt.zyl.data.volley.toolbox.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *///from ww w .ja va 2 s . c om @SuppressWarnings("deprecation") /* protected */ static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { switch (request.getMethod()) { case Request.Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Request.Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } case Method.HEAD: return new HttpHead(request.getUrl()); case Method.OPTIONS: return new HttpOptions(request.getUrl()); case Method.TRACE: return new HttpTrace(request.getUrl()); case Method.PATCH: { HttpPatch patchRequest = new HttpPatch(request.getUrl()); patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(patchRequest, request); return patchRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:com.example.hellojni.HelloJni.java
@Override public void onResume() { super.onResume(); /*/*from www.j a v a 2s. co m*/ ByteBuffer buffer = vk.doStuff(); if (buffer != null) { Log.d("HelloJni", "Got buffer from jni:" + buffer.capacity()); Bitmap frame = Bitmap.createBitmap(192, 144, Config.ARGB_8888); frame.copyPixelsFromBuffer(buffer); ImageView iv = new ImageView(this); iv.setImageBitmap(frame); setContentView(iv); } */ /* new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... params) { vk.doStuff(frame); return null; } }.execute(); */ new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... ps) { HttpPost post = new HttpPost("http://192.168.0.187:45631/service"); AVMap avMap = new AVMap("air.connect.Request"); avMap.put("requestURL", "http://192.168.0.187:45631/service"); avMap.put("clientVersion", 240); avMap.put("serviceName", "browseService"); avMap.put("methodName", "getItems"); avMap.put("clientIdentifier", "89eae483355719f119d698e8d11e8b356525ecfb"); AVMap params = new AVMap("air.video.BrowseRequest"); params.put("folderId", "5ADB62B1BB62E0190E4B9C07159265C48F322D84"); params.put("preloadDetails", 0); List<Object> list = new ArrayList<Object>(); list.add(params); avMap.put("parameters", list); AVStream avStream = new AVStream(); avStream.write(avMap, 0); post.setEntity(new ByteArrayEntity(avStream.finish())); try { HttpResponse response = httpClient.execute(post); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); response.getEntity().writeTo(outputStream); AVStream result = new AVStream(outputStream.toByteArray()); AVMap foo = (AVMap) result.read(); Log.d("AirVideo", foo.getName()); Log.d("AirVideo", foo.toString()); AVMap results = (AVMap) foo.get("result"); final List<Object> items = (List<Object>) results.get("items"); runOnUiThread(new Runnable() { public void run() { // TODO Auto-generated method stub for (Object o : items) { AVMap item = (AVMap) o; listAdapter.add((String) item.get("name")); } } }); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }.execute(); }
From source file:org.wso2.dss.integration.test.odata.ODataTestUtils.java
public static int sendPATCH(String endpoint, String content, Map<String, String> headers) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpPatch httpPatch = new HttpPatch(endpoint); for (String headerType : headers.keySet()) { httpPatch.setHeader(headerType, headers.get(headerType)); }/*from w w w . java 2s . c om*/ if (null != content) { HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8")); if (headers.get("Content-Type") == null) { httpPatch.setHeader("Content-Type", "application/json"); } httpPatch.setEntity(httpEntity); } HttpResponse httpResponse = httpClient.execute(httpPatch); return httpResponse.getStatusLine().getStatusCode(); }