无法使用ms graph设置个人资料照片

g52tjvyc  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(460)

我尝试了以下方法:

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得到二进制字符串,但是webservice仍然说我的文件不是图像。我必须承认我很困惑

oymdgrw7

oymdgrw71#

此端点将原始图像作为输入,而不是base64编码版本。检查文档。在请求体中,包括请求体中照片的二进制数据。
我看到你在使用httpclient。我想要以下内容:
代码段:

using (HttpClient client = new HttpClient())
{
    var authResult = await AuthenticationHelper.Current.GetAccessTokenAsync();
    if (authResult.Status != AuthenticationStatus.Success)
        return;
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authResult.AccessToken);
    Uri userPhotoEndpoint = new Uri(AuthenticationHelper.GraphEndpointId + "users/" + userIdentifier + "/Photo/$value");
    StreamContent content = new StreamContent(image);
    content.Headers.Add("Content-Type", "application/octet-stream");
    using (HttpResponseMessage response = await client.PutAsync(userPhotoEndpoint, content))
    {
        response.EnsureSuccessStatusCode();
    }
}
bd1hkmkf

bd1hkmkf2#

我终于明白了!ms-graph服务等待的只是文件本身(带有头部图像/jpeg)。这样我上传了照片:

file = new File(filePath);

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

如dev所述,不需要使用base64转换它

相关问题