微信开票上传PDF,提示数据格式错误?
发布于 4 年前 作者 jietan 9477 次浏览 来自 官方Issues

想看看大家上传PDF是怎么做的,可以分享一下代码或者软件测试案例吗?

下面是我的代码

public static String uploadPdfFile(String accessToken, File file){//
    HttpPost httpPost = new HttpPost(accessToken);
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
    httpPost.setConfig(requestConfig);
    //2.3 设置请求实体,封装了请求参数
    HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("pdf",
            new FileBody(file, ContentType.create("multipart/form-data", Consts.UTF_8), file.getName())).build();

    httpPost.setEntity(requestEntity);
    try {
        response = httpClient.execute(httpPost, new BasicHttpContext());
        System.out.println(response);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Exception("上传PDF文件至微信,请求失败");
        }
        HttpEntity entity = response.getEntity();//
        if (entity != null) {
            String resultStr = EntityUtils.toString(entity, "utf-8");
            System.out.println(resultStr);
            JSONObject result = JSON.parseObject(resultStr);
            int errcode = (Integer)result.get("errcode");
            if(errcode != 0){
                throw new Exception("上传PDF文件至微信失败");
            }
            return result.getString("s_media_id");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
回到顶部