System.CalloutException:对于输入字符串:“password@app.fluidsurveys.com”

时间:2013-04-16 10:02:23

标签: salesforce apex-code

我正在尝试访问Sales Force中的流体调查API。我使用以下代码但它响应错误。

控制器类的代码是:

public class fluidSurvey{
    public String tst{set;get;}
    public String result{get;set;}

    public PageReference chk() {

        //if (!ApexPages.hasMessages())
            result=getData();

        return null;
    }
 public String getData()
   {
       HttpRequest req= new HttpRequest();
       Http http = new Http();
       req.setMethod('GET');
       String url = 'https://username:password@app.fluidsurveys.com/api/v2/surveys/';
       req.setEndpoint(url);
       HttpResponse res = http.send(req);
       String json =  res.getBody().replace('\n','');
       tst = json;
        try {
            JSONObject j = new JSONObject( json );
            return parseJson(j);
        } catch (JSONObject.JSONException e) {
            return 'Error parsing JSON response from Google: '+e;
        }

   }

   public String parseJson(JSONObject resp){
       String detail =resp.getString('total');

       return detail;
   }
}

并且顶点页面的代码是:

<apex:page controller="fluidSurvey">
  <!-- Begin Default Content REMOVE THIS -->
   <h1>Fluid Survey</h1>
   <apex:form >
       <apex:outputText value="{!tst}"></apex:outputText>
      <apex:commandButton value="Submit" action="{!chk}"/>
  </apex:form>
</apex:page>

但是当我点击提交按钮时,会产生以下错误:

System.CalloutException: For input string: "password@app.fluidsurveys.com"
Error is in expression '{!chk}' in component <apex:page> in page fluid-page

2 个答案:

答案 0 :(得分:4)

您需要明确设置授权标头。

请尝试以下代码:

public String getData()
{
    HttpRequest req= new HttpRequest();
    Http http = new Http();
    req.setMethod('GET');
    String authString = 'username:password';
    String url = 'https://app.fluidsurveys.com/api/v2/surveys/';
    req.setEndpoint(url);

    req.setHeader('Authorization', 'BASIC ' + EncodingUtil.base64Encode(Blob.valueOf(authString)));

    HttpResponse res = http.send(req);
    String json =  res.getBody().replace('\n','');

    try {
        JSONObject j = new JSONObject( json );
        return parseJson(j);
    } catch (JSONObject.JSONException e) {
        return 'Error parsing JSON response from Google: '+e;
    }
}

答案 1 :(得分:0)

我不相信您可以使用用户名:password @ host格式在Callouts的URL中传递身份验证信息,您必须在请求中显式设置Authentication HTTP标头,以便传递凭据。 (具体如何执行此操作取决于服务器支持的身份验证类型)