Warm tip: This article is reproduced from serverfault.com, please click

java-无法使用ms图设置个人资料照片

(java - can't set profile photo with ms graph)

发布于 2020-12-01 21:39:59

我尝试了以下方法:

filePath = sourcePath + "ash.jpg";

byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath));
String encodedString = Base64.getEncoder().encodeToString(fileContent);

imagePayload = HttpRequest.BodyPublishers.ofString(encodedString)

def url='https://graph.microsoft.com/v1.0/users/<myuser>/photo/$value';

HttpClient httpClient = HttpClient.newBuilder()
                        .version(HttpClient.Version.HTTP_2)
                        .build();

HttpRequest request = HttpRequest.newBuilder()
                      .uri(URI.create(url))
                      .method("PUT",imagePayload)
                      .header("Content-Type", "image/jpeg")
                      .header("Authorization", "Bearer " + token)
                      .build();

回报不断告诉我:

发生内部服务器错误。操作失败。,你选择的文件不是图像。请选择其他文件。

我想有效载荷是错误的,但是他到底期望什么?MS Graph文档指出它应该对jpeg图像进行二进制重新设置

具有以下内容:

filePath = sourcePath + "ash.jpg";

file = new File(filePath);

BufferedImage image = ImageIO.read(file);

ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", b);

byte[] jpgByteArray = b.toByteArray();

StringBuilder sb = new StringBuilder();
for (byte by : jpgByteArray)
    sb.append(Integer.toBinaryString(by & 0xFF));

imagePayloadAsString = sb.toString();

imagePayload = HttpRequest.BodyPublishers.ofString(imagePayloadAsString)

我得到带Os和1s的二进制字符串,但是Web服务仍然说我的文件不是图像。我必须承认我很困惑

Questioner
laloune
Viewed
1
laloune 2020-12-17 06:17:21

我终于明白了!ms graph服务正在等待的只是文件本身(带有标头图片/ jpeg)。因此,我设法上传了照片:


file = new File(filePath);

imagePayload = HttpRequest.BodyPublishers.ofFile(file.toPath())

如开发人员所述,无需使用base64进行转换