【问题标题】:How do I upload an image to the wordpress media API using java如何使用 java 将图像上传到 wordpress 媒体 API
【发布时间】:2022-01-25 11:16:49
【问题描述】:

如何使用 java 将图像上传到 wordpress API? Rest API 的路径是 wp-json/wp/v2/media

【问题讨论】:

    标签: java wordpress api


    【解决方案1】:

    您可以上传图像文件(某些文件类型 - 默认启用常用图像格式(此处为 WP 接受的完整上传格式列表:https://wordpress.com/support/accepted-filetypes/

    我用来完成此操作的代码如下:

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpHeaders;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String encoded_cred = Base64.getEncoder().encodeToString(("username:pw").getBytes());
            String extension = "";
            String mime = "";
            String fileName = F.getName();
            int i = fileName.lastIndexOf('.');
            if (i > 0) {
                extension = fileName.substring(i + 1);
            }
            if (extension.equalsIgnoreCase("png")) {
                mime = "image/png";
            }
            if (extension.equalsIgnoreCase("jpeg")) {
                mime = "image/jpeg";
            }
        
            //endpoint and entity
            String uri = "https://www.<domain>.com/wp-json/wp/v2/media";
            HttpEntity entity = MultipartEntityBuilder.create()
                    .addBinaryBody("file", new FileInputStream(F), ContentType.create(mime), fileName)
                    .build();
    
    
            //request and execution
            HttpPost media = new HttpPost(uri);
            media.setEntity(entity);
            media.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded_cred);
            CloseableHttpResponse response = httpClient.execute(media);
            String resp = EntityUtils.toString(response.getEntity());
    

    我的 pomfile 使用了这些,虽然版本不一定相同:

    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.9</version>
        </dependency>
    </dependencies>
    

    【讨论】:

      猜你喜欢
      • 2023-02-11
      • 2020-01-14
      • 1970-01-01
      • 2016-11-17
      • 2019-03-15
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多