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


Java HttpHeaders.setContentType方法代码示例

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


在下文中一共展示了HttpHeaders.setContentType方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testCreateZoneRecordSendsCorrectRequest

import com.google.api.client.http.HttpHeaders; //导入方法依赖的package包/类
@Test
public void testCreateZoneRecordSendsCorrectRequest() throws DnsimpleException, IOException {
  String accountId = "1010";
  String zoneId = "example.com";
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType("application/json");
  HashMap<String, Object> attributes = new HashMap<String, Object>();
  attributes.put("name", "www");

  Client client = mockAndExpectClient("https://api.dnsimple.com/v2/1010/zones/example.com/records", HttpMethods.POST, headers, attributes, resource("createZoneRecord/created.http"));

  client.zones.createZoneRecord(accountId, zoneId, attributes);
}
 
开发者ID:dnsimple,项目名称:dnsimple-java,代码行数:14,代码来源:ZoneRecordsTest.java

示例2: setUp

import com.google.api.client.http.HttpHeaders; //导入方法依赖的package包/类
@Before
public void setUp() throws ConfigException {
	config = new ConfigBuilder().setApiKey("test").setEndpoint("http://localhost:8001/").build();
   	handler = new Handler(config);
   	headers = new HttpHeaders();
	headers.setContentType("application/json");
	headers.set("postmen-api-key", "some-api-key");
	headers.set("x-postmen-agent", "java-sdk-1.0.0");
	headers.set("connection", "keep-alive");
}
 
开发者ID:postmen,项目名称:postmen-sdk-java,代码行数:11,代码来源:HandlerExecuteTest.java

示例3: execute

import com.google.api.client.http.HttpHeaders; //导入方法依赖的package包/类
/**
 * Executes the HTTP request for a temporary or long-lived token.
 *
 * @throws IOException 
 */

public final HttpResponse execute() throws IOException  {
	
	ApacheHttpTransport.Builder builder = new ApacheHttpTransport.Builder();
	
	if(this.proxyEnabled) {
		builder.setProxy(this.proxy);
	}
	
	transport = builder.build();

	if(usePost && body != null){
		requestBody = ByteArrayContent.fromString(null, body);
	}
	
	HttpHeaders headers = new HttpHeaders();
	headers.setUserAgent(config.getUserAgent());
	headers.setAccept(accept != null ? accept : config.getAccept());
	
	headers.setContentType(contentType == null ? "application/xml" : contentType);
	
	if(ifModifiedSince != null) {
		//System.out.println("Set Header " + this.ifModifiedSince);
		headers.setIfModifiedSince(this.ifModifiedSince);	
	}

	HttpRequestFactory requestFactory = transport.createRequestFactory();
	HttpRequest request;
	HttpResponse response = null;
	
	request = requestFactory.buildRequest(this.httpMethod, Url, requestBody);
	request.setConnectTimeout(connectTimeout);
	request.setReadTimeout(readTimeout);
	request.setHeaders(headers);
	
	createParameters().intercept(request);
	
	response = request.execute();
	response.setContentLoggingLimit(0);


	return response;
}
 
开发者ID:XeroAPI,项目名称:Xero-Java,代码行数:49,代码来源:OAuthRequestResource.java

示例4: send

import com.google.api.client.http.HttpHeaders; //导入方法依赖的package包/类
/** Uploads {@code reportBytes} to ICANN, returning whether or not it succeeded. */
public boolean send(byte[] reportBytes, String reportFilename) throws XmlException, IOException {
  validateReportFilename(reportFilename);
  GenericUrl uploadUrl = new GenericUrl(makeUrl(reportFilename));
  HttpRequest request =
      httpTransport
          .createRequestFactory()
          .buildPutRequest(uploadUrl, new ByteArrayContent(CSV_UTF_8.toString(), reportBytes));

  HttpHeaders headers = request.getHeaders();
  headers.setBasicAuthentication(getTld(reportFilename) + "_ry", password);
  headers.setContentType(CSV_UTF_8.toString());
  request.setHeaders(headers);
  request.setFollowRedirects(false);

  HttpResponse response = null;
  logger.infofmt(
      "Sending report to %s with content length %s",
      uploadUrl.toString(), request.getContent().getLength());
  boolean success = true;
  try {
    response = request.execute();
    byte[] content;
    try {
      content = ByteStreams.toByteArray(response.getContent());
    } finally {
      response.getContent().close();
    }
    logger.infofmt(
        "Received response code %s with content %s",
        response.getStatusCode(), new String(content, UTF_8));
    XjcIirdeaResult result = parseResult(content);
    if (result.getCode().getValue() != 1000) {
      success = false;
      logger.warningfmt(
          "PUT rejected, status code %s:\n%s\n%s",
          result.getCode(),
          result.getMsg(),
          result.getDescription());
    }
  } finally {
    if (response != null) {
      response.disconnect();
    } else {
      success = false;
      logger.warningfmt(
          "Received null response from ICANN server at %s", uploadUrl.toString());
    }
  }
  return success;
}
 
开发者ID:google,项目名称:nomulus,代码行数:52,代码来源:IcannHttpReporter.java

示例5: getConfig

import com.google.api.client.http.HttpHeaders; //导入方法依赖的package包/类
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void getConfig(String urlPath, String token, String projectId,
    String cloudRegion, String registryId, String deviceId, String version)
    throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  urlPath = urlPath + devicePath + "/config?local_version=" + version;

  HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) {
          request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
      });

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  HttpHeaders heads = new HttpHeaders();

  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  req.setHeaders(heads);
  ExponentialBackOff backoff = new ExponentialBackOff.Builder()
      .setInitialIntervalMillis(500)
      .setMaxElapsedTimeMillis(900000)
      .setMaxIntervalMillis(6000)
      .setMultiplier(1.5)
      .setRandomizationFactor(0.5)
      .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
  InputStream in = res.getContent();

  System.out.println(CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)));
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:43,代码来源:HttpExample.java

示例6: publishMessage

import com.google.api.client.http.HttpHeaders; //导入方法依赖的package包/类
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void publishMessage(String payload, String urlPath, String messageType,
    String token, String projectId, String cloudRegion, String registryId, String deviceId)
    throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  String urlSuffix = messageType.equals("event") ? "publishEvent" : "setState";

  // Data sent through the wire has to be base64 encoded.
  Base64.Encoder encoder = Base64.getEncoder();

  String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));

  urlPath = urlPath + devicePath + ":" + urlSuffix;


  final HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) {
          request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
      });

  HttpHeaders heads = new HttpHeaders();
  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  // Add post data. The data sent depends on whether we're updating state or publishing events.
  JSONObject data = new JSONObject();
  if (messageType.equals("event")) {
    data.put("binary_data", encPayload);
  } else {
    JSONObject state = new JSONObject();
    state.put("binary_data", encPayload);
    data.put("state", state);
  }

  ByteArrayContent content = new ByteArrayContent(
      "application/json", data.toString().getBytes("UTF-8"));

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  req.setHeaders(heads);
  req.setContent(content);
  req.setRequestMethod("POST");
  ExponentialBackOff backoff = new ExponentialBackOff.Builder()
      .setInitialIntervalMillis(500)
      .setMaxElapsedTimeMillis(900000)
      .setMaxIntervalMillis(6000)
      .setMultiplier(1.5)
      .setRandomizationFactor(0.5)
      .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));

  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:63,代码来源:HttpExample.java

示例7: writeTo

import com.google.api.client.http.HttpHeaders; //导入方法依赖的package包/类
@Override
public void writeTo(OutputStream out) throws IOException {

    Writer writer = new OutputStreamWriter(out, getCharset());
    String boundary = getBoundary();

    for (Part part : parts) {
        HttpHeaders headers = new HttpHeaders().setAcceptEncoding(null);
        if (part.headers != null) {
            headers.fromHttpHeaders(part.headers);
        }
        headers.setContentEncoding(null).setUserAgent(null).setContentType(null).setContentLength(null);
        // analyze the content
        HttpContent content = part.content;
        StreamingContent streamingContent = null;
        String contentDisposition = String.format("form-data; name=\"%s\"", part.name);
        if (part.filename != null) {
            headers.setContentType(content.getType());
            contentDisposition += String.format("; filename=\"%s\"", part.filename);
        }
        headers.set("Content-Disposition", contentDisposition);
        HttpEncoding encoding = part.encoding;
        if (encoding == null) {
            streamingContent = content;
        } else {
            headers.setContentEncoding(encoding.getName());
            streamingContent = new HttpEncodingStreamingContent(content, encoding);
        }
        // write separator
        writer.write(TWO_DASHES);
        writer.write(boundary);
        writer.write(NEWLINE);
        // write headers
        HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);
        // write content
        if (streamingContent != null) {
            writer.write(NEWLINE);
            writer.flush();
            streamingContent.writeTo(out);
            writer.write(NEWLINE);
        }
    }
    // write end separator
    writer.write(TWO_DASHES);
    writer.write(boundary);
    writer.write(TWO_DASHES);
    writer.write(NEWLINE);
    writer.flush();
}
 
开发者ID:kmonaghan,项目名称:Broadsheet.ie-Android,代码行数:50,代码来源:MultipartFormDataContent.java

示例8: createHttpHeaders

import com.google.api.client.http.HttpHeaders; //导入方法依赖的package包/类
private HttpHeaders createHttpHeaders() {
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType("application/xml");
  headers.setUserAgent(session.getUserAgent());
  return headers;
}
 
开发者ID:googleads,项目名称:googleads-java-lib,代码行数:7,代码来源:BatchJobUploader.java


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