类org.apache.http.client.entity.EntityBuilder源码实例Demo

下面列出了怎么用org.apache.http.client.entity.EntityBuilder的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: turbo-rpc   文件: UserServiceJsonHttpClientImpl.java
@Override
public CompletableFuture<Boolean> createUser(User user) {
	try {
		byte[] bytes = objectMapper.writeValueAsBytes(user);

		HttpPost request = new HttpPost(URL_CREATE_USER);
		HttpEntity entity = EntityBuilder.create().setBinary(bytes).build();
		request.setEntity(entity);

		CloseableHttpResponse response = client.execute(request);

		String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

		return CompletableFuture.completedFuture("true".equals(result));
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
源代码2 项目: raptor   文件: HttpclientRaptorServerBenchmark.java
@Benchmark
public void test(Blackhole bh) {
    String body = "{\"name\":\"ppdai\"}";
    String url = "http://localhost:" + port + "/raptor/com.ppdai.framework.raptor.proto.Simple/sayHello";
    HttpUriRequest request = RequestBuilder.post(url)
            .addHeader("connection", "Keep-Alive")
            .setEntity(EntityBuilder.create().setText(body).setContentType(ContentType.APPLICATION_JSON).build())
            .build();
    String responseBody;
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(100);
        response.getEntity().writeTo(bos);
        responseBody = new String(bos.toByteArray(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException("error", e);
    }
    bh.consume(responseBody);
}
 
源代码3 项目: raptor   文件: HttpclientSpringMvcBenchmark.java
@Benchmark
public void test(Blackhole bh) {
    String body = "{\"name\":\"ppdai\"}";
    String url = "http://localhost:" + port + "/raptor/com.ppdai.framework.raptor.proto.Simple/sayHello";
    HttpUriRequest request = RequestBuilder.post(url)
            .addHeader("connection", "Keep-Alive")
            .setEntity(EntityBuilder.create().setText(body).setContentType(ContentType.APPLICATION_JSON).build())
            .build();
    String responseBody;
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(100);
        response.getEntity().writeTo(bos);
        responseBody = new String(bos.toByteArray(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException("error", e);
    }
    bh.consume(responseBody);
}
 
源代码4 项目: devops-cm-client   文件: CMODataAbapClient.java
public void updateTransport(Transport transport) throws IOException, URISyntaxException, ODataException, UnexpectedHttpResponseException
{
  Edm edm = getEntityDataModel();
  try (CloseableHttpClient client = clientFactory.createClient()) {
    
    HttpPut put = requestBuilder.updateTransport(transport.getTransportID());
    put.setHeader("x-csrf-token", getCSRFToken());
    EdmEntityContainer entityContainer = edm.getDefaultEntityContainer();
    EdmEntitySet entitySet = entityContainer.getEntitySet(TransportRequestBuilder.getEntityKey());
    URI rootUri = new URI(endpoint.toASCIIString() + "/");
    EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(rootUri).build();
    ODataResponse response = null;
    try {
        response = EntityProvider.writeEntry(put.getHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue(), entitySet,transport.getValueMap(), properties);
        put.setEntity(EntityBuilder.create().setStream(response.getEntityAsStream()).build());
        try (CloseableHttpResponse httpResponse = client.execute(put)) {
            hasStatusOrFail(httpResponse, SC_OK, HttpStatus.SC_NO_CONTENT);
        }
    }  finally {
        if(response != null) response.close();
    }
  }
}
 
源代码5 项目: devops-cm-client   文件: CMODataAbapClient.java
public Transport createTransport(Map<String, Object> transport) throws IOException, URISyntaxException, ODataException, UnexpectedHttpResponseException
{
  try (CloseableHttpClient client = clientFactory.createClient()) {
    HttpPost post = requestBuilder.createTransport();
    post.setHeader("x-csrf-token", getCSRFToken());
    EdmEntityContainer entityContainer = getEntityDataModel().getDefaultEntityContainer();
    EdmEntitySet entitySet = entityContainer.getEntitySet(TransportRequestBuilder.getEntityKey());
    URI rootUri = new URI(endpoint.toASCIIString() + "/");
    EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(rootUri).build();
    ODataResponse marshaller = null;

    try {
      marshaller = EntityProvider.writeEntry(post.getHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue(), entitySet, transport, properties);
      post.setEntity(EntityBuilder.create().setStream(marshaller.getEntityAsStream()).build());

      try(CloseableHttpResponse httpResponse = client.execute(post)) {
        hasStatusOrFail(httpResponse, SC_CREATED);
        return getTransport(httpResponse);
      }
    } finally {
        if(marshaller != null) marshaller.close();
    }
  }
}
 
@Override
public boolean createUser(User user) {
	try {
		byte[] bytes = objectMapper.writeValueAsBytes(user);

		HttpPost request = new HttpPost(URL_CREATE_USER);
		HttpEntity entity = EntityBuilder.create().setBinary(bytes).build();
		request.setEntity(entity);

		CloseableHttpResponse response = client.execute(request);

		String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

		return "true".equals(result);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
@Override
public boolean createUser(User user) {
	try {
		byte[] bytes = objectMapper.writeValueAsBytes(user);

		HttpPost request = new HttpPost(URL_CREATE_USER);
		HttpEntity entity = EntityBuilder.create().setBinary(bytes).build();
		request.setEntity(entity);

		CloseableHttpResponse response = client.execute(request);

		String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

		return "true".equals(result);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
源代码8 项目: jshERP   文件: HttpClient.java
/**
 * 采用Post方式发送请求,获取响应数据
 *
 * @param url        url地址
 * @param param  参数值键值对的字符串
 * @return
 */
public static String httpPost(String url, String param) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpPost post = new HttpPost(url);
        EntityBuilder builder = EntityBuilder.create();
        builder.setContentType(ContentType.APPLICATION_JSON);
        builder.setText(param);
        post.setEntity(builder.build());

        CloseableHttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        logger.info("状态:"+statusCode+"数据:"+data);
        return data;
    } catch(Exception e){
        throw new RuntimeException(e.getMessage());
    } finally {
        try{
            client.close();
        }catch(Exception ex){ }
    }
}
 
源代码9 项目: geowave   文件: GeoServerIT.java
public static boolean enableWfs() throws ClientProtocolException, IOException {
  final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
  final CloseableHttpClient httpclient = clientAndContext.getLeft();
  final HttpClientContext context = clientAndContext.getRight();
  try {
    final HttpPut command =
        new HttpPut(
            ServicesTestEnvironment.GEOSERVER_REST_PATH
                + "/services/wfs/workspaces/"
                + ServicesTestEnvironment.TEST_WORKSPACE
                + "/settings");
    command.setHeader("Content-type", "text/xml");
    command.setEntity(
        EntityBuilder.create().setFile(
            new File("src/test/resources/wfs-requests/wfs.xml")).setContentType(
                ContentType.TEXT_XML).build());
    final HttpResponse r = httpclient.execute(command, context);
    return r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
  } finally {
    httpclient.close();
  }
}
 
源代码10 项目: geowave   文件: GeoServerIT.java
public static boolean enableWms() throws ClientProtocolException, IOException {
  final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
  final CloseableHttpClient httpclient = clientAndContext.getLeft();
  final HttpClientContext context = clientAndContext.getRight();
  try {
    final HttpPut command =
        new HttpPut(
            ServicesTestEnvironment.GEOSERVER_REST_PATH
                + "/services/wms/workspaces/"
                + ServicesTestEnvironment.TEST_WORKSPACE
                + "/settings");
    command.setHeader("Content-type", "text/xml");
    command.setEntity(
        EntityBuilder.create().setFile(
            new File("src/test/resources/wfs-requests/wms.xml")).setContentType(
                ContentType.TEXT_XML).build());
    final HttpResponse r = httpclient.execute(command, context);
    return r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
  } finally {
    httpclient.close();
  }
}
 
源代码11 项目: geowave   文件: GeoServerIT.java
public boolean createLayers() throws ClientProtocolException, IOException {
  final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
  final CloseableHttpClient httpclient = clientAndContext.getLeft();
  final HttpClientContext context = clientAndContext.getRight();
  try {
    final HttpPost command =
        new HttpPost(
            ServicesTestEnvironment.GEOSERVER_REST_PATH
                + "/workspaces/"
                + ServicesTestEnvironment.TEST_WORKSPACE
                + "/datastores/"
                + dataStoreOptions.getGeoWaveNamespace()
                + "/featuretypes");
    command.setHeader("Content-type", "text/xml");
    command.setEntity(
        EntityBuilder.create().setText(geostuff_layer).setContentType(
            ContentType.TEXT_XML).build());
    final HttpResponse r = httpclient.execute(command, context);
    return r.getStatusLine().getStatusCode() == Status.CREATED.getStatusCode();
  } finally {
    httpclient.close();
  }
}
 
源代码12 项目: geowave   文件: GeoServerIT.java
public boolean queryPoint() throws Exception {
  final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
  final CloseableHttpClient httpclient = clientAndContext.getLeft();
  final HttpClientContext context = clientAndContext.getRight();
  try {
    final HttpPost command = createWFSTransaction(httpclient, "1.1.0");
    command.setEntity(
        EntityBuilder.create().setText(query).setContentType(ContentType.TEXT_XML).build());
    final HttpResponse r = httpclient.execute(command, context);

    final boolean result = r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
    if (result) {
      final String content = getContent(r);
      System.out.println(content);
      final String patternX = "34.6815818";
      final String patternY = "35.1828408";
      // name space check as well
      return content.contains(patternX)
          && content.contains(patternY)
          && content.contains(ServicesTestEnvironment.TEST_WORKSPACE + ":geometry");
    }
    return false;
  } finally {
    httpclient.close();
  }
}
 
源代码13 项目: bonita-studio   文件: UpdateCustomPageRequest.java
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
    final HttpPut updatePageRequest = new HttpPut(
            String.format(getURLBase() + PORTAL_UPDATE_PAGE_API, pageToUpdate.getId()));
    updatePageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
    final EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setContentType(ContentType.APPLICATION_JSON);
    if(pageToUpdate.getProcessDefinitionId() != null) {
        entityBuilder.setText(String.format("{\"pageZip\" : \"%s\", \"processDefinitionId\" : \"%s\" }", uploadedFileToken,pageToUpdate.getProcessDefinitionId()));
    }else {
        entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
    }
    updatePageRequest.setEntity(entityBuilder.build());
    final HttpResponse response = httpClient.execute(updatePageRequest);
    final int status = response.getStatusLine().getStatusCode();
    String responseContent = contentAsString(response);
    if (status != HttpURLConnection.HTTP_OK) {
        throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
    }
    return responseContent;
}
 
源代码14 项目: bonita-studio   文件: AddCustomPageRequest.java
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
    final HttpPost addPageRequest = new HttpPost(getURLBase() + PORTAL_ADD_PAGE_API);
    addPageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
    final EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setContentType(ContentType.APPLICATION_JSON);
    entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
    addPageRequest.setEntity(entityBuilder.build());
    final HttpResponse response = httpClient.execute(addPageRequest);
    final int status = response.getStatusLine().getStatusCode();
    String responseContent = contentAsString(response);
    if (status != HttpURLConnection.HTTP_OK) {
        throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
    }
    return responseContent;
}
 
源代码15 项目: datasync   文件: HttpUtilityTest.java
@Test
public void testHttpPost() throws Exception {
    URI postUri = new URIBuilder()
            .setScheme("https")
            .setHost(DOMAIN.split("//")[1])
            .setPath("/datasync/id/" + UNITTEST_DATASET_ID)
            .build();
    InputStream is = new FileInputStream(new File("src/test/resources/example_patch.sdiff"));
    byte[] data = IOUtils.toByteArray(is);
    HttpEntity entity = EntityBuilder.create().setBinary(data).build();

    try(CloseableHttpResponse response = http.post(postUri, entity);
        InputStream body = response.getEntity().getContent()) {
        // uncomment the test below, when di2 is running in prod
        /*
        TestCase.assertEquals(201, response.getStatusLine().getStatusCode());
        String blobId = mapper.readValue(response.getEntity().getContent(), BlobId.class).blobId;
        TestCase.assertNotNull(blobId);
        */
    }
}
 
源代码16 项目: data-highway   文件: HttpHandlerTest.java
@Test
public void simplePost() throws Exception {
  stubFor(post(urlEqualTo("/foo")).willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody("bar")));

  try (HttpHandler handler = new HttpHandler(url, options)) {
    HttpEntity entity = EntityBuilder.create().setText("baz").build();
    HttpResponse response = handler.post("foo", entity);
    try (Reader reader = new InputStreamReader(response.getEntity().getContent())) {
      assertThat(CharStreams.toString(reader), is("bar"));
    }
  }

  verify(postRequestedFor(urlEqualTo("/foo")).withRequestBody(equalTo("baz")));
}
 
源代码17 项目: DataSphereStudio   文件: AzkabanProjectService.java
/**
 * parameters:
 * name = value
 * description=value
 *
 * @param project
 * @param session
 * @throws AppJointErrorException
 */
@Override
public Project createProject(Project project, Session session) throws AppJointErrorException {
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("action", "create"));
    params.add(new BasicNameValuePair("name", project.getName()));
    params.add(new BasicNameValuePair("description", project.getDescription()));
    HttpPost httpPost = new HttpPost(projectUrl);
    httpPost.addHeader(HTTP.CONTENT_ENCODING, HTTP.IDENTITY_CODING);
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(session.getCookies()[0]);
    HttpEntity entity = EntityBuilder.create()
            .setContentType(ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))
            .setParameters(params).build();
    httpPost.setEntity(entity);
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    try {
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        response = httpClient.execute(httpPost);
        HttpEntity ent = response.getEntity();
        String entStr = IOUtils.toString(ent.getContent(), "utf-8");
        logger.error("新建工程 {}, azkaban 返回的信息是 {}", project.getName(), entStr);
        String message = AzkabanUtils.handleAzkabanEntity(entStr);
        if (!"success".equals(message)) {
            throw new AppJointErrorException(90008, "新建工程失败, 原因:" + message);
        }
    } catch (Exception e) {
        logger.error("创建工程失败:", e);
        throw new AppJointErrorException(90009, e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
    return null;
}
 
/** Uploads the next byte chunk of the media item. */
private HttpResponse uploadNextChunk(String uploadUrl, long receivedByteCount)
    throws IOException {
  // Reads data from input stream
  byte[] dataChunk = new byte[optimalChunkSize];
  int readByteCount = request.readData(dataChunk);

  // Avoid uploading the whole chunk when only a part of it contains data
  if (readByteCount < optimalChunkSize) {
    dataChunk = trimByteArray(dataChunk, readByteCount);
  }

  HttpPost httpPost = createAuthenticatedPostRequest(uploadUrl);
  httpPost.addHeader(UPLOAD_PROTOCOL_HEADER, UPLOAD_PROTOCOL_VALUE);

  if (receivedByteCount + readByteCount == request.getFileSize()) {
    httpPost.addHeader(
        UPLOAD_COMMAND_HEADER, String.join(",", UploadCommands.UPLOAD, UploadCommands.FINALIZE));
  } else {
    httpPost.addHeader(UPLOAD_COMMAND_HEADER, UploadCommands.UPLOAD);
  }

  httpPost.addHeader(UPLOAD_OFFSET_HEADER, String.valueOf(receivedByteCount));
  httpPost.addHeader(UPLOAD_SIZE_HEADER, String.valueOf(readByteCount));
  httpPost.setEntity(EntityBuilder.create().setBinary(dataChunk).build());

  CloseableHttpClient httpClient =
      HttpClientBuilder.create()
          .useSystemProperties()
          .setDefaultRequestConfig(getRequestConfig())
          .build();
  return httpClient.execute(httpPost);
}
 
源代码19 项目: timer   文件: ParamsSession.java
public final ParamsSession addParams(Map paramsMap) throws UnsupportedEncodingException {
    Objects.requireNonNull(paramsMap);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    Iterator<Map.Entry<String, String>> iterator = paramsMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    EntityBuilder entityBuilder= (EntityBuilder) this.getProviderService().provider();
    entityBuilder.setParameters(nameValuePairs);
    return this;
}
 
源代码20 项目: lol-client-java-api   文件: ClientApi.java
private <T extends HttpEntityEnclosingRequestBase> void addJsonBody(Object jsonObject, T method) {
    method.setEntity(
            EntityBuilder.create()
                    .setText(GSON.toJson(jsonObject))
                    .setContentType(ContentType.APPLICATION_JSON)
                    .build()
    );
}
 
源代码21 项目: sparkler   文件: ApacheHttpRestClient.java
public String httpPostRequest(String uriString, String extractedText) throws IOException {
    URI uri = URI.create(uriString);

    HttpPost httpPost = new HttpPost(uri);
    httpPost.addHeader("Content-Type", "text/plain");
    HttpEntity reqEntity = EntityBuilder.create().setText(URLEncoder.encode(extractedText, "UTF-8")).build();
    httpPost.setEntity(reqEntity);

    String responseBody = httpClient.execute(httpPost, this.responseHandler);

    return responseBody;
}
 
源代码22 项目: zerocode   文件: BasicHttpClient.java
/**
 * This is the usual http request builder most widely used using Apache Http Client. In case you want to build
 * or prepare the requests differently, you can override this method.
 *
 * Please see the following request builder to handle file uploads.
 *     - BasicHttpClient#createFileUploadRequestBuilder(java.lang.String, java.lang.String, java.lang.String)
 *
 * You can override this method via @UseHttpClient(YourCustomHttpClient.class)
 *
 * @param httpUrl
 * @param methodName
 * @param reqBodyAsString
 * @return
 */
public RequestBuilder createDefaultRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) {
    RequestBuilder requestBuilder = RequestBuilder
            .create(methodName)
            .setUri(httpUrl);

    if (reqBodyAsString != null) {
        HttpEntity httpEntity = EntityBuilder.create()
                .setContentType(APPLICATION_JSON)
                .setText(reqBodyAsString)
                .build();
        requestBuilder.setEntity(httpEntity);
    }
    return requestBuilder;
}
 
源代码23 项目: geowave   文件: GeoServerIT.java
public boolean createPoint() throws Exception {
  final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
  final CloseableHttpClient httpclient = clientAndContext.getLeft();
  final HttpClientContext context = clientAndContext.getRight();
  try {
    final HttpPost command = createWFSTransaction(httpclient, "1.1.0");
    command.setEntity(
        EntityBuilder.create().setText(insert).setContentType(ContentType.TEXT_XML).build());
    final HttpResponse r = httpclient.execute(command, context);
    return r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
  } finally {
    httpclient.close();
  }
}
 
源代码24 项目: geowave   文件: GeoServerIT.java
public String lockPoint() throws Exception {
  final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
  final CloseableHttpClient httpclient = clientAndContext.getLeft();
  final HttpClientContext context = clientAndContext.getRight();
  try {
    final HttpPost command = createWFSTransaction(httpclient, "1.1.0");
    command.setEntity(
        EntityBuilder.create().setText(lock).setContentType(ContentType.TEXT_XML).build());
    final HttpResponse r = httpclient.execute(command, context);

    final boolean result = r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
    if (result) {
      final String content = getContent(r);
      final String pattern = "lockId=\"([^\"]+)\"";

      // Create a Pattern object
      final Pattern compiledPattern = Pattern.compile(pattern);
      final Matcher matcher = compiledPattern.matcher(content);
      if (matcher.find()) {
        return matcher.group(1);
      }
      return content;
    }
    return null;
  } finally {
    httpclient.close();
  }
}
 
源代码25 项目: datasync   文件: DeltaImporter2Publisher.java
/**
 * Chunks up the signature patch file into ~4MB chunks and posts these to delta-importer-2
 * @param patchStream an inputStream to the patch
 * @param datasetId the 4x4 of the dataset being patched
 * @return the list of blobIds corresponding to each successful post
 */
private List<String> postPatchBlobs(InputStream patchStream, String datasetId, int chunkSize) throws
        IOException, URISyntaxException, HttpException {
    updateStatus("Chunking and posting the diff", 0, false, "");
    System.out.println("Creating the diff...");

    URI postingPath = baseUri.setPath(datasyncPath + "/" + datasetId).build();
    List<String> blobIds = new LinkedList<>();
    byte[] bytes = new byte[chunkSize];
    StatusLine statusLine;
    int status;
    int bytesRead;

    while ((bytesRead = Utils.readChunk(patchStream, bytes, 0, bytes.length)) != -1) {
        System.out.println("\tUploading " + bytesRead + " bytes of the diff");
        byte[] chunk = bytesRead == bytes.length ? bytes : Arrays.copyOf(bytes, bytesRead);
        HttpEntity entity = EntityBuilder.create().setBinary(chunk).build();
        int retries = 0;
        do {
            try(CloseableHttpResponse response = http.post(postingPath, entity)) {
                statusLine = response.getStatusLine();
                status = statusLine.getStatusCode();
                if (status != HttpStatus.SC_CREATED) {
                    retries += 1;
                } else {
                    String blobId = mapper.readValue(response.getEntity().getContent(), BlobId.class).blobId;
                    blobIds.add(blobId);
                }
            }
        } while (status != HttpStatus.SC_CREATED && retries < httpRetries);
        //We hit the max number of retries without success and should throw an exception accordingly.
        if (retries >= httpRetries) throw new HttpException(statusLine.toString());
        updateStatus("Uploading file", 0, false, bytesRead + " bytes");
        System.out.println("\tUploaded " + bytesRead + " bytes");
    }
    return blobIds;
}
 
源代码26 项目: emissary   文件: MoveToAdapter.java
/**
 * Send a moveTo call to a remote machine
 * 
 * @param place the four-tuple of the place we are heading to
 * @param agent the MobileAgent that is moving
 * @return status of operation including body if successful
 */
public EmissaryResponse outboundMoveTo(final String place, final IMobileAgent agent) {

    String url = null;

    // Move to actions can be load-balanced out to
    // a virtual IP address:port if so configured
    if (VIRTUAL_MOVETO_ADDR != null) {
        url = VIRTUAL_MOVETO_PROTOCOL + "://" + VIRTUAL_MOVETO_ADDR + "/";
    } else {
        url = KeyManipulator.getServiceHostURL(place);
    }
    url += CONTEXT + "/MoveTo.action";

    final HttpPost method = new HttpPost(url);
    method.setHeader("Content-type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
    final List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    nvps.add(new BasicNameValuePair(PLACE_NAME, place));
    nvps.add(new BasicNameValuePair(MOVE_ERROR_COUNT, Integer.toString(agent.getMoveErrorCount())));

    final DirectoryEntry[] iq = agent.getItineraryQueueItems();
    for (int j = 0; j < iq.length; j++) {
        nvps.add(new BasicNameValuePair(ITINERARY_ITEM, iq[j].getKey()));
    }

    try {
        // This is an 8859_1 String
        final String agentData = PayloadUtil.serializeToString(agent.getPayloadForTransport());
        nvps.add(new BasicNameValuePair(AGENT_SERIAL, agentData));
    } catch (IOException iox) {
        // TODO This will probably need looked at when redoing the moveTo
        logger.error("Cannot serialize agent data", iox);
        BasicHttpResponse response =
                new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Cannot serialize agent data");
        response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build());
        return new EmissaryResponse(response);
    }

    method.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName("8859_1")));

    // Add a cookie to the outbound header if we are posting
    // to the virtual IP for load balancing
    if (VIRTUAL_MOVETO_ADDR != null) {
        final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, KeyManipulator.getServiceClassname(place));
        cookie.setDomain(VIRTUAL_MOVETO_ADDR.substring(0, VIRTUAL_MOVETO_ADDR.indexOf(":")));
        cookie.setPath(COOKIE_PATH);
        return send(method, cookie);
    }
    return send(method);
}
 
源代码27 项目: emissary   文件: DirectoryAdapter.java
/**
 * Handle the packaging and sending of an addPlaces call to a remote directory. Sends multiple keys on the same place
 * with the same cost/quality and description if the description, cost and quality lists are only size 1. Uses a
 * distinct description/cost/quality for each key when there are enough values
 *
 * @param parentDirectory the url portion of the parent directory location
 * @param entryList the list of directory entries to add
 * @param propagating true if going downstream
 * @return status of operation
 */
public EmissaryResponse outboundAddPlaces(final String parentDirectory, final List<DirectoryEntry> entryList, final boolean propagating) {
    if (disableAddPlaces) {
        BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "Not accepting remote add places");
        response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build());
        return new EmissaryResponse(response);
    } else {
        final String parentDirectoryUrl = KeyManipulator.getServiceHostURL(parentDirectory);
        final HttpPost method = new HttpPost(parentDirectoryUrl + CONTEXT + "/RegisterPlace.action");

        final String parentLoc = KeyManipulator.getServiceLocation(parentDirectory);
        // Separate it out into lists
        final List<String> keyList = new ArrayList<String>();
        final List<String> descList = new ArrayList<String>();
        final List<Integer> costList = new ArrayList<Integer>();
        final List<Integer> qualityList = new ArrayList<Integer>();
        for (final DirectoryEntry d : entryList) {
            keyList.add(d.getKey());
            descList.add(d.getDescription());
            costList.add(Integer.valueOf(d.getCost()));
            qualityList.add(Integer.valueOf(d.getQuality()));
        }

        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(TARGET_DIRECTORY, parentLoc));

        for (int count = 0; count < keyList.size(); count++) {
            nvps.add(new BasicNameValuePair(ADD_KEY + count, keyList.get(count)));
            // possibly use the single desc/cost/qual for each key
            if (descList.size() > count) {
                String desc = descList.get(count);
                if (desc == null) {
                    desc = "No description provided";
                }
                nvps.add(new BasicNameValuePair(ADD_DESCRIPTION + count, desc));
            }
            if (costList.size() > count) {
                nvps.add(new BasicNameValuePair(ADD_COST + count, costList.get(count).toString()));
            }
            if (qualityList.size() > count) {
                nvps.add(new BasicNameValuePair(ADD_QUALITY + count, qualityList.get(count).toString()));
            }
        }
        nvps.add(new BasicNameValuePair(ADD_PROPAGATION_FLAG, Boolean.toString(propagating)));
        method.setEntity(new UrlEncodedFormEntity(nvps, Charset.defaultCharset()));
        return send(method);
    }
}
 
源代码28 项目: timer   文件: EntityBuilderProvider.java
public EntityBuilder provider() {
    this.entityBuilder= EntityBuilder.create();
    return entityBuilder;
}
 
源代码29 项目: timer   文件: ParamsSession.java
public ParamsSession(HttpEntityProviderService<EntityBuilder> providerService) {
    super(providerService);
}
 
源代码30 项目: sakai   文件: UrkundAPIUtil.java
public static String postDocument(String baseUrl, String receiverAddress, String externalId, UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout){
		String ret = null;
		
		RequestConfig.Builder requestBuilder = RequestConfig.custom();
		requestBuilder = requestBuilder.setConnectTimeout(timeout);
		requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);
		
		HttpClientBuilder builder = HttpClientBuilder.create();     
		builder.setDefaultRequestConfig(requestBuilder.build());
		try (CloseableHttpClient httpClient = builder.build()) {
			
			
			HttpPost httppost = new HttpPost(baseUrl+"submissions/"+receiverAddress+"/"+externalId);
			//------------------------------------------------------------
			EntityBuilder eBuilder = EntityBuilder.create();
			eBuilder.setBinary(submission.getContent());

			httppost.setEntity(eBuilder.build());
			//------------------------------------------------------------
			if(StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
				addAuthorization(httppost, urkundUsername, urkundPassword);
			}
			//------------------------------------------------------------
			httppost.addHeader("Accept", "application/json");
			httppost.addHeader("Content-Type", submission.getMimeType());
			httppost.addHeader("Accept-Language", submission.getLanguage());
			httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
			httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
			httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
			httppost.addHeader("x-urkund-subject", submission.getSubject());
			httppost.addHeader("x-urkund-message", submission.getMessage());
			//------------------------------------------------------------

			HttpResponse response = httpClient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			if (resEntity != null) {
				ret = EntityUtils.toString(resEntity);
				EntityUtils.consume(resEntity);
			}

		} catch (IOException e) {
			log.error("ERROR uploading File : ", e);
		}
		
		
		return ret;
}
 
 类所在包
 类方法
 同包方法