错误java.lang.illegalargumentexception:无效的开始或结束

nmpmafwu  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(1098)

我试图测试salesforce的restapi callout,它通过apex代码进行oauth身份验证,并运行到下面的错误 Line: 12, Column: 1 System.UnexpectedException: java.lang.IllegalArgumentException: invalid start or end ```
public with sharing class RetrieveD365Data {
//@future (callout=true)
public void getD365Data() {
RetrieveAzureToken atz = new RetrieveAzureToken();
String bearer = atz.getAzureData();
Http http = new Http();
HttpRequest req1 = new HttpRequest();
req1.setEndpoint('https://dev-xyz.com/data/Customers');
req1.setMethod('GET');
req1.setHeader('Authorization','Bearer '+bearer);
HttpResponse res1 = http.send(req1); //Error is thrown in this line
System.debug('Response Body=========' + res1.getBody());
}
}

在哪里 `RetrieveAzureToken` 类如下所示,这与预期一样工作,我能够用承载令牌返回响应

global class RetrieveAzureToken {

private final String clientId = 'xxxxxxxxx';
private final String clientSecret = 'xxxxxxxxxx';

public String getAzureData()
{
    String reqbody = 'grant_type=client_credentials&client_id='+clientId+'&client_secret='+clientSecret;
    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setBody(reqbody);
    req.setMethod('POST');
    req.setEndpoint('https://login.microsoftonline.com/tenant/oauth2/token');
    HttpResponse res = h.send(req);
    deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
    system.debug('Token from Azure :' + resp1.access_token);  
    return  resp1.access_token;
}

public class deserializeResponse
{
    public String token_type;
    public String expires_in;
    public String ext_expires_in;
    public String expires_on;
    public String not_before;
    public String resource;
    public String access_token;
}

}

请让我想想我在这里错过了什么。
dzhpxtsq

dzhpxtsq1#

使用基于jersey的rest服务和使用httpurlconnection的客户端,我可以观察到相同的illegalargumentexception。
场景如下:
rest服务定义了一个资源函数

@GET
public void throw401() {
  throw new javax.ws.rs.NotAuthorizedException("");
}

此资源由客户端作为

HttpURLConncection c = (HttpURLConnection)url.openConnection();
int status = c.getResponseCode(); // throws IllegalArgumentException: invalid start or end

我的解决方案是将资源更改为:

@GET
public void throw401() {
  throw new javax.ws.rs.NotAuthorizedException(Response.status(Response.UNAUTHORIZED));
}

我认为-没有证明-构造函数notauthorizedexception(string)生成一个没有身份验证模式的www authenitcate头。这会导致在httpurlconnection尝试解析IllegalArgumentException时引发该选项。构造器notauthorizedexception(resonse)只发送一个状态401,没有www身份验证头。

相关问题