当前位置: 首页>>代码示例>>Java>>正文


Java HttpContent类代码示例

本文整理汇总了Java中com.google.api.client.http.HttpContent的典型用法代码示例。如果您正苦于以下问题:Java HttpContent类的具体用法?Java HttpContent怎么用?Java HttpContent使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


HttpContent类属于com.google.api.client.http包,在下文中一共展示了HttpContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: postRequest

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
protected <E> E postRequest(String path, Object body, Class<E> responseType){
    try {
        URI uri = uri(path);
        GenericUrl url = new GenericUrl(uri);

        if ( logger.isDebugEnabled() ){
            logger.debug("Request POSTed into botframework api " + uri + ":");
            logger.debug(JSON_FACTORY.toPrettyString(body));
        }
        HttpContent content = new JsonHttpContent(JSON_FACTORY,body);
        HttpRequest request = requestFactory.buildPostRequest(url,content);
        E response = (E) request.execute().parseAs(responseType);
        if ( logger.isDebugEnabled() ){
            logger.debug("Response back from botframework api:");
            logger.debug(JSON_FACTORY.toPrettyString(response));
        }
        return response;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:bots4j,项目名称:msbotframework,代码行数:22,代码来源:ConnectorClient.java

示例2: postRequestAsync

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
protected Future<HttpResponse> postRequestAsync(String path, Object body){
    try {
        URI uri = uri(path);
        GenericUrl url = new GenericUrl();
        if ( logger.isDebugEnabled() ){
            logger.debug("Request POSTed into botframework api " + uri + ":");
            logger.debug(JSON_FACTORY.toPrettyString(body));
        }
        HttpContent content = new JsonHttpContent(JSON_FACTORY,body);
        HttpRequest request = requestFactory.buildPostRequest(url,content);
        if ( this.executor != null ){
            return request.executeAsync(this.executor);
        }
        else{
            return request.executeAsync();
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:bots4j,项目名称:msbotframework,代码行数:22,代码来源:ConnectorClient.java

示例3: sendPostMultipart

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
public static int sendPostMultipart(String urlString, Map<String, String> parameters)
    throws IOException {

  MultipartContent postBody = new MultipartContent()
      .setMediaType(new HttpMediaType("multipart/form-data"));
  postBody.setBoundary(MULTIPART_BOUNDARY);

  for (Map.Entry<String, String> entry : parameters.entrySet()) {
    HttpContent partContent = ByteArrayContent.fromString(  // uses UTF-8 internally
        null /* part Content-Type */, entry.getValue());
    HttpHeaders partHeaders = new HttpHeaders()
        .set("Content-Disposition",  "form-data; name=\"" + entry.getKey() + "\"");

    postBody.addPart(new MultipartContent.Part(partHeaders, partContent));
  }

  GenericUrl url = new GenericUrl(new URL(urlString));
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url, postBody);
  request.setHeaders(new HttpHeaders().setUserAgent(CloudToolsInfo.USER_AGENT));
  request.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS);
  request.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);

  HttpResponse response = request.execute();
  return response.getStatusCode();
}
 
开发者ID:GoogleCloudPlatform,项目名称:google-cloud-eclipse,代码行数:26,代码来源:HttpUtil.java

示例4: create

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
public boolean create(String name, String rules) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("rules", rules);

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/policy/" + name),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
开发者ID:streamsets,项目名称:datacollector,代码行数:24,代码来源:Policy.java

示例5: getSecret

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
protected Secret getSecret(String path, String method, HttpContent content) throws VaultException {
  try {
    HttpRequest request = getRequestFactory().buildRequest(
        method,
        new GenericUrl(getConf().getAddress() + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.parseAs(Secret.class);
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
开发者ID:streamsets,项目名称:datacollector,代码行数:19,代码来源:VaultEndpoint.java

示例6: putDroplets

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
public void putDroplets(String userName, List<Droplet> droplets) throws Exception {
    try {
        System.out.println("Perform droplet search ....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);

        HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets);
        HttpRequest request = httpRequestFactory.buildPostRequest(
                new GenericUrl(DROPLET_POST_URL + userName),
                content);

        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw e;
    }
}
 
开发者ID:ZanyGnu,项目名称:GeoNote,代码行数:19,代码来源:DropletServer.java

示例7: loggingRequest

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
public static void loggingRequest(HttpRequest request) {
    if ( LOGGER.isDebugEnabled()) {
        HttpContent httpContent = request.getContent();
        String content = "";
        if (httpContent != null){
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                request.getContent().writeTo(output);
                content = output.toString();

            } catch (IOException ex) {
                LOGGER.warn("Error io during get content request " + ex.getMessage());
                content = ex.getMessage();
            }
        }
        LOGGER.debug("[GloboDNSAPI request] " + request.getRequestMethod() + " URL:" + request.getUrl() + " Content:" + content);
    }
}
 
开发者ID:globocom,项目名称:GloboDNS-Client,代码行数:19,代码来源:HttpUtil.java

示例8: loadDataFromNetwork

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
/**
 * <pre>
 * status[drink_id]=50fb3d16ce007c40fc00080d&status[dealer_id]=52cd8b5e7a58b40eae004e40&status[status]=1
 * </pre>
 */
@Override
public DrinkStatus loadDataFromNetwork() throws Exception {
    Map<String, String> tempParameters = new HashMap<>();
    tempParameters.put("status[drink_id]", drinkId);
    tempParameters.put("status[dealer_id]",dealerId);
    tempParameters.put("status[status]",drinkStatus.getStatusId());

    HttpContent tempContent = new UrlEncodedContent(tempParameters);
    HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(URL_BASE + URL_STATUS_UPDATE), tempContent);
    GsonBuilder tmpBuilder = new GsonBuilder();
    tmpBuilder.registerTypeAdapter(Dealer.class, new DealerDetailsDeserializer());
    Gson tempGson = tmpBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    DrinkStatus tmpDealer;
    try (InputStream in = request.execute().getContent()) {
        tmpDealer = tempGson.fromJson(new InputStreamReader(in), DrinkStatus.class);
        if (tmpDealer == null) {
            Log.e(LOGTAG, "No dealer details downloaded");
        } else {
            Log.i(LOGTAG, "Downloaded dealer details: " + tmpDealer);
        }
    }

    return tmpDealer;
}
 
开发者ID:guerda,项目名称:Matekarte,代码行数:30,代码来源:DrinkStatusUpdateRequest.java

示例9: uploadTestFile

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
private static File uploadTestFile(ProducerTemplate template, String testName) {
    File fileMetadata = new File();
    fileMetadata.setTitle(GoogleDriveIntegrationTest.class.getName()+"."+testName+"-"+ UUID.randomUUID().toString());
    final String content = "Camel rocks!\n" //
            + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()) + "\n" //
            + "user: " + System.getProperty("user.name");
    HttpContent mediaContent = new ByteArrayContent("text/plain", content.getBytes(StandardCharsets.UTF_8));

    final Map<String, Object> headers = new HashMap<>();
    // parameter type is com.google.api.services.drive.model.File
    headers.put("CamelGoogleDrive.content", fileMetadata);
    // parameter type is com.google.api.client.http.AbstractInputStreamContent
    headers.put("CamelGoogleDrive.mediaContent", mediaContent);

    return template.requestBodyAndHeaders("google-drive://drive-files/insert", null, headers, File.class);
}
 
开发者ID:wildfly-extras,项目名称:wildfly-camel,代码行数:17,代码来源:GoogleDriveIntegrationTest.java

示例10: testMissingBody

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
@Test
public void testMissingBody() throws IOException {
  HttpContent httpContent = new ByteArrayContent("application/json",
      new byte[]{});

  GenericUrl url = new GenericUrl();
  url.setScheme("http");
  url.setHost("localhost");
  url.setPort(port);
  url.setRawPath("/tox");

  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest httpRequest = requestFactory.buildPostRequest(url, httpContent);

  HttpResponse httpResponse = httpRequest.execute();
  Assert.assertEquals(HttpStatusCodes.STATUS_CODE_OK, httpResponse.getStatusCode());
  Reader reader = new InputStreamReader(httpResponse.getContent(), Charsets.UTF_8);

  JsonRpcResponse response = JsonRpcResponse.fromJson(new JsonParser().parse(reader)
      .getAsJsonObject());

  Assert.assertTrue(response.isError());
  Assert.assertEquals(400, response.error().status().code());
}
 
开发者ID:jsilland,项目名称:piezo,代码行数:25,代码来源:HttpJsonRpcServerTest.java

示例11: extractPayload

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
private String extractPayload(HttpHeaders headers, @Nullable HttpContent content) {
  StringBuilder messageBuilder = new StringBuilder();
  if (headers != null) {
    appendMapAsString(messageBuilder, headers);
  }
  if (content != null) {
    messageBuilder.append(String.format("%nContent:%n"));
    if (content instanceof UrlEncodedContent) {
      UrlEncodedContent encodedContent = (UrlEncodedContent) content;
      appendMapAsString(messageBuilder, Data.mapOf(encodedContent.getData()));
    } else if (content != null) {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      try {
        content.writeTo(byteStream);
        messageBuilder.append(byteStream.toString(StandardCharsets.UTF_8.name()));
      } catch (IOException e) {
        messageBuilder.append("Unable to read request content due to exception: " + e);
      }
    }
  }
  return messageBuilder.toString();
}
 
开发者ID:googleads,项目名称:googleads-java-lib,代码行数:23,代码来源:ReportServiceLogger.java

示例12: serializeContent

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
private byte[] serializeContent(HttpRequest request) {

        byte[] contentBytes;
        try {
            HttpContent content = request.getContent();
            if (content == null) {
                return new byte[]{};
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            content.writeTo(bos);
            contentBytes = bos.toByteArray();
            // for non-retryable content, reset the content for downstream handlers
            if (!content.retrySupported()) {
                HttpContent newContent = new ByteArrayContent(content.getType(), contentBytes);
                request.setContent(newContent);
            }
            return contentBytes;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
开发者ID:akamai,项目名称:AkamaiOPEN-edgegrid-java,代码行数:22,代码来源:GoogleHttpClientEdgeGridRequestSigner.java

示例13: createNewLineString

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
/**
 * Creates a new row in Google Fusion Tables representing the track as a line
 * segment.
 * 
 * @param fusiontables fusion tables
 * @param tableId the table id
 * @param track the track
 */
private void createNewLineString(Fusiontables fusiontables, String tableId, Track track)
    throws IOException {
  String values = SendFusionTablesUtils.formatSqlValues(track.getName(), track.getDescription(),
      SendFusionTablesUtils.getKmlLineString(track.getLocations()));
  String sql = "INSERT INTO " + tableId + " (name,description,geometry) VALUES " + values;
  HttpContent content = ByteArrayContent.fromString(null, "sql=" + sql);
  GoogleUrl url = new GoogleUrl("https://www.googleapis.com/fusiontables/v1/query");
  fusiontables.getRequestFactory().buildPostRequest(url, content).execute();
}
 
开发者ID:Plonk42,项目名称:mytracks,代码行数:18,代码来源:SendFusionTablesAsyncTask.java

示例14: postAndParse

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
<T> T postAndParse(GenericUrl url, HttpContent content, Class<T> cls) {
  try {
    HttpRequest request = this.requestFactory.buildPostRequest(url, content);
    return executeAndParse(request, cls);
  } catch (IOException ex) {
    throw new ConnectException("Exception encountered while calling salesforce", ex);
  }
}
 
开发者ID:jcustenborder,项目名称:kafka-connect-salesforce,代码行数:9,代码来源:SalesforceRestClientImpl.java

示例15: authenticate

import com.google.api.client.http.HttpContent; //导入依赖的package包/类
@Override
public AuthenticationResponse authenticate() {
  HttpContent formContent = buildAuthContent();
  this.authentication = postAndParse(this.authenticateUrl, formContent, AuthenticationResponse.class);

  if (null == this.config.instance || this.config.instance.isEmpty()) {
    this.baseUrl = new GenericUrl(this.authentication.instance_url());
  } else {
    this.baseUrl = new GenericUrl(this.config.instance);
  }

  return this.authentication;
}
 
开发者ID:jcustenborder,项目名称:kafka-connect-salesforce,代码行数:14,代码来源:SalesforceRestClientImpl.java


注:本文中的com.google.api.client.http.HttpContent类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。