Java Code Examples for org.apache.http.entity.ContentType#create()

The following examples show how to use org.apache.http.entity.ContentType#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KylinClient.java    From kylin with Apache License 2.0 7 votes vote down vote up
@Override
public void connect() throws IOException {
    HttpPost post = new HttpPost(baseUrl() + "/kylin/api/user/authentication");
    addHttpHeaders(post);
    StringEntity requestEntity = new StringEntity("{}", ContentType.create("application/json", "UTF-8"));
    post.setEntity(requestEntity);

    try {
        HttpResponse response = httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
            throw asIOException(post, response);
        }
    } finally {
        post.releaseConnection();
    }
}
 
Example 2
Source File: RemoteTransformerClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
HttpEntity getRequestEntity(ContentReader reader, String sourceMimetype, String sourceExtension,
                                    String targetExtension, long timeoutMs, String[] args, StringJoiner sj)
{
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    ContentType contentType = ContentType.create(sourceMimetype);
    builder.addBinaryBody("file", reader.getContentInputStream(), contentType, "tmp."+sourceExtension);
    builder.addTextBody("targetExtension", targetExtension);
    sj.add("targetExtension" + '=' + targetExtension);
    for (int i=0; i< args.length; i+=2)
    {
        if (args[i+1] != null)
        {
            builder.addTextBody(args[i], args[i + 1]);

            sj.add(args[i] + '=' + args[i + 1]);
        }
    }

    if (timeoutMs > 0)
    {
        String timeoutMsString = Long.toString(timeoutMs);
        builder.addTextBody("timeout", timeoutMsString);
        sj.add("timeout=" + timeoutMsString);
    }
    return builder.build();
}
 
Example 3
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void createFolderSimpleJSON(CloseableHttpClient httpclient)
			throws UnsupportedEncodingException, IOException {

//		CloseableHttpClient httpclient = HttpClients.createDefault();

		// This will create a tree starting from the Default workspace
		String folderPath = "/Default/USA/NJ/Fair Lawn/createSimple/JSON";
		String input = "{ \"folderPath\" : \"" + folderPath + "\" }";
		System.out.println(input);

		HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/folder/createSimpleJSON");
		StringEntity entity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));
		httppost.setEntity(entity);

		CloseableHttpResponse response = httpclient.execute(httppost);
		try {
			HttpEntity rent = response.getEntity();
			if (rent != null) {
				String respoBody = EntityUtils.toString(rent, "UTF-8");
				System.out.println(respoBody);
			}
		} finally {
			response.close();
		}
	}
 
Example 4
Source File: HttpRpcClient.java    From tangyuan2 with GNU General Public License v3.0 6 votes vote down vote up
private String sendPostRequest(String url, byte[] buffer, String header) throws Throwable {
	// TODO: 默认值设置
	CloseableHttpClient httpclient = HttpClients.createDefault();
	try {
		URI uri = new URI(url);
		HttpPost httpost = new HttpPost(uri);
		ByteArrayEntity byteArrayEntity = new ByteArrayEntity(buffer, ContentType.create(header, "UTF-8"));
		httpost.setEntity(byteArrayEntity);
		CloseableHttpResponse response = httpclient.execute(httpost);
		try {
			int status = response.getStatusLine().getStatusCode();
			if (status != 200) {
				throw new Exception("Unexpected response status: " + status);
			}
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
		} finally {
			response.close();
		}
	} finally {
		httpclient.close();
	}
}
 
Example 5
Source File: CommentsRestClient.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String doPostLoginJSON(String username, String password) throws Exception {
	
	CloseableHttpClient httpclient = getHTTPClient(username, password);

	String input = "{ \"username\" : \"" +username +"\", \"password\" : \"" +password +"\" }";
	System.out.println(input);

	StringEntity entity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));
	HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/auth/login");
	httppost.setEntity(entity);

	CloseableHttpResponse response = httpclient.execute(httppost);
	try {
		HttpEntity rent = response.getEntity();
		if (rent != null) {
			String respoBody = EntityUtils.toString(rent, "UTF-8");
			System.out.println(respoBody);
			return respoBody;
		}
	} finally {
		response.close();
	}

	return null;
}
 
Example 6
Source File: GalaxyFDSClient.java    From galaxy-fds-sdk-java with Apache License 2.0 5 votes vote down vote up
private PutObjectResult uploadWithFile(String bucketName, String objectName, File file,
    FDSObjectMetadata metadata) throws GalaxyFDSClientException {
  if (this.fdsConfig.isMd5CalculateEnabled()) {
    throw new GalaxyFDSClientException(
        "Upload with File object and MD5 calculate enabled is not supported");
  }

  ContentType contentType = ContentType.APPLICATION_OCTET_STREAM;
  if (metadata == null) {
    metadata = new FDSObjectMetadata();
  }

  if (metadata.getContentType() != null) {
    contentType = ContentType.create(metadata.getContentType());
  }

  URI uri = formatUri(fdsConfig.getUploadBaseUri(),
    bucketName + "/" + (objectName == null ? "" : objectName), (SubResource[]) null);
  FileEntity requestEntity = new FileEntity(file, contentType);

  HttpMethod m = objectName == null ? HttpMethod.POST : HttpMethod.PUT;
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, m, contentType, metadata,
    null, null, requestEntity);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest,
    objectName == null ? Action.PostObject : Action.PutObject);

  return (PutObjectResult) fdsHttpClient.processResponse(response, PutObjectResult.class,
    m.name() + " object [" + objectName + "] to bucket [" + bucketName + "]");
}
 
Example 7
Source File: Rest.java    From components with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor sets schema(http or https), host(google.com) and port number(8080) using one hostPort parameter
 * 
 * @param hostPort URL
 */
public Rest(String hostPort) {
    headers = new LinkedList<>();
    if (!hostPort.endsWith("/")) {
        hostPort = hostPort + "/";
    }
    this.hostPort = hostPort;

    contentType = ContentType.create("application/json", StandardCharsets.UTF_8);

    executor = Executor.newInstance(createHttpClient());
    executor.use(new BasicCookieStore());
}
 
Example 8
Source File: HttpBodyPart.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private ContentType constructContentTypeObject() {

        ContentType _contentType = null;
        if (contentType != null) {
            if (charset != null) {
                _contentType = ContentType.create(contentType, charset);
            } else {
                _contentType = ContentType.create(contentType);
            }
        }

        return _contentType;
    }
 
Example 9
Source File: AbstractRequestEs.java    From DataLink with Apache License 2.0 5 votes vote down vote up
protected void setEntity(HttpRequestBase request , byte[] content){
	
	if((request instanceof HttpEntityEnclosingRequestBase) && content != null){
		 ContentType contentType = ContentType.create("application/json", "UTF-8");
		 HttpEntity httpEntity = new ByteArrayEntity(content, contentType);
		 ((HttpEntityEnclosingRequestBase)request).setEntity(httpEntity);
	}
}
 
Example 10
Source File: StoreRow.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
protected Callable<Response> callable() {
  return new Callable<Response>() {
    @Override
    public Response call() throws Exception {
      Document document = XmlUtils.createDocument();

      Element root = document.createElement( ELEMENT_CELL_SET );
      document.appendChild( root );

      Element row = document.createElement( ELEMENT_ROW );
      row.setAttribute( ATTRIBUTE_KEY, Base64.encodeBase64String( rowId.getBytes( StandardCharsets.UTF_8 ) ) );
      root.appendChild( row );

      for( InsertableColumn column : columns ) {
        Element cell = document.createElement( ELEMENT_CELL );
        cell.setAttribute( ATTRIBUTE_COLUMN, column.encodedName() );
        if( column.time() != null ) {
          cell.setAttribute( ATTRIBUTE_TIMESTAMP, column.time().toString() );
        }
        cell.setTextContent( column.encodedValue() );
        row.appendChild( cell );
      }

      StringWriter writer = new StringWriter();
      Transformer t = XmlUtils.getTransformer( true, false, 0, false );
      XmlUtils.writeXml( document, writer, t );

      URIBuilder uri = uri( HBase.SERVICE_PATH, "/", tableName, "/false-row-key" );
      HttpPost request = new HttpPost( uri.build() );
      HttpEntity entity = new StringEntity( writer.toString(), ContentType.create( "text/xml", StandardCharsets.UTF_8 ) );
      request.setEntity( entity );

      return new Response( execute( request ) );
    }
  };
}
 
Example 11
Source File: RefineHTTPClient.java    From p3-batchrefine with Apache License 2.0 5 votes vote down vote up
private ContentType contentType(URL url, URLConnection connection) throws IOException {
    String type = connection.getContentType();

    if (type.equals("content/unknown") && url.getProtocol().equals("file")) {
        // Probes file.
        type = Files.probeContentType(new File(url.getFile()).toPath());
    }

    return type != null ? ContentType.create(type) : ContentType.DEFAULT_TEXT.withCharset(Charset.forName("UTF-8"));
}
 
Example 12
Source File: Postpone.java    From FreeServer with Apache License 2.0 5 votes vote down vote up
/**
     * 提交延期记录
     * @param yunClient
     * @param url
     * @param file
     */
    public void sendAbei(UserInfo info, HttpClient yunClient, String url, File file, Map<String,String> cookieMap, int bz) throws Exception {
        log.info("开始提交延期记录!!!");
//        HttpPost httpPost = new HttpPost(CommCode.getYunUrl(bz,1));
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

        //三丰云和阿贝云文件提交方式不一样
        if(bz==0) {
            multipartEntityBuilder.addBinaryBody("yanqi_img",file);
        }else{
            multipartEntityBuilder.addBinaryBody("yanqi_img",file, ContentType.IMAGE_PNG,"postpone.png");
        }
        multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
        multipartEntityBuilder.addTextBody("cmd","free_delay_add" ,contentType);
        multipartEntityBuilder.addTextBody("ptype","vps" ,contentType);
        multipartEntityBuilder.addTextBody("url",url ,contentType);
        String postRes = HttpUtil.getPostRes(yunClient, ParamUtil.getYunUrl(bz,1), multipartEntityBuilder.build());

        JSONObject json = JSONObject.fromObject(postRes);
        log.info("提交延期记录返回结果:"+json.toString());
        try{
            if("提交成功".equals(json.getString("msg"))){
                log.info("提交延期记录成功!!!");
            }else{
                log.info("提交延期记录失败,删除发布博客!!!");
                Sina.deleteBlog(info,url,cookieMap);
            }
        }catch (Exception e){
            log.info("提交延期记录失败,删除发布博客!!!");
            Sina.deleteBlog(info,url,cookieMap);
        }
        file.delete();

    }
 
Example 13
Source File: ApacheHttpClient.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private ContentType getContentType(Request request) {
    ContentType contentType = ContentType.DEFAULT_TEXT;
    for (Map.Entry<String, Collection<String>> entry : request.headers().entrySet()) {
        if (entry.getKey().equalsIgnoreCase("Content-Type")) {
            Collection values = entry.getValue();
            if (values != null && !values.isEmpty()) {
                contentType = ContentType.create(entry.getValue().iterator().next(), request.charset());
                break;
            }
        }
    }
    return contentType;
}
 
Example 14
Source File: QCRestHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
@Override
public void setPostEntity(File file, HttpPost httppost) {
    httppost.setHeader("Content-Type", "application/octet-stream");
    httppost.setHeader("Slug", file.getName());
    HttpEntity e = new FileEntity(file, ContentType.create(MIME.getType(file)));
    httppost.setEntity(e);
}
 
Example 15
Source File: RestApiTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateIfNonExistingUpdateInDocTrue() throws Exception {
    Request request = new Request("http://localhost:" + getFirstListenPort() + update_test_create_if_non_existient_uri);
    HttpPut httpPut = new HttpPut(request.getUri());
    StringEntity entity = new StringEntity(update_test_create_if_non_existient_doc, ContentType.create("application/json"));
    httpPut.setEntity(entity);
    assertThat(doRest(httpPut).body, is(update_test_create_if_non_existing_response));
    assertThat(getLog(), containsString("CREATE IF NON EXISTENT IS TRUE"));
}
 
Example 16
Source File: SoapRawClient.java    From tutorial-soap-spring-boot-cxf with MIT License 4 votes vote down vote up
private ContentType contentTypeTextXmlUtf8() {
	return ContentType.create(ContentType.TEXT_XML.getMimeType(), Consts.UTF_8);
}
 
Example 17
Source File: DefaultHandler.java    From Photato with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected Response getResponse(String path, Map<String, String> query) throws Exception {
    return new Response(200, new FileEntity(folderRoot.resolve("index.html").toFile(), ContentType.create("text/html; charset=UTF-8")));
}
 
Example 18
Source File: HttpClient.java    From ats-framework with Apache License 2.0 2 votes vote down vote up
/**
 * Set the request body using content in a string.
 *
 * @param string The request
 * @param contentType The content type, e.g. 'text/xml'
 */
@PublicAtsApi
public void setRequestBody( String string, String contentType ) {

    requestBody = new StringEntity(string, ContentType.create(contentType));
}
 
Example 19
Source File: HttpClient.java    From ats-framework with Apache License 2.0 2 votes vote down vote up
/**
 * Set the request body using content in a file.
  *
 * @param file The file containing the request
  * @param contentType The content type, e.g. 'text/xml'
 * @param charset The charset, e.g. 'UTF-8'
  */
@PublicAtsApi
public void setRequestBody( File file, String contentType, String charset ) {

    requestBody = new FileEntity(file, ContentType.create(contentType, charset));
}
 
Example 20
Source File: HttpClient.java    From ats-framework with Apache License 2.0 2 votes vote down vote up
/**
 * Set the request body using content in a byte array.
 *
 * @param bytes The request
 * @param contentType The content type, e.g. 'text/xml'
 */
@PublicAtsApi
public void setRequestBody( byte[] bytes, String contentType ) {

    requestBody = new ByteArrayEntity(bytes, ContentType.create(contentType));
}