服务器无法识别(?)cUrl HttpPost参数

时间:2016-01-03 00:52:45

标签: android json post curl httpclient

我正在尝试从服务器获取授权密钥。在文档中,他们声明我可以通过执行以下curl命令来检索一个:

$ curl --data "grant_type=authorization_code&code=603372224265" https://gerard2.zportal.nl/api/v2/oauth/token`

我已按照stackoverflow中的说明操作并生成以下内容:

@Override
protected String doInBackground(String... params) {
    mAuthorizationCode = params[0];
    mSchoolCode = params[1];

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://" + mSchoolCode + ".zportal.nl/api/v2/oauth/token");
    try{
        List<NameValuePair> nameValuePairs = new ArrayList<>(2);
        httppost.setHeader("Content-Type", "application/json");
        httppost.setHeader("Accept", "application/json");
        nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nameValuePairs.add(new BasicNameValuePair("code", mAuthorizationCode));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));

        HttpParams parameters = httppost.getParams();
        HttpConnectionParams.setConnectionTimeout(parameters, 45000);
        HttpConnectionParams.setSoTimeout(parameters, 45000);

        HttpResponse response = httpClient.execute(httppost);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        while((line = reader.readLine()) != null){
            Log.e(LOG_TAG, line);
        }
    }catch(ClientProtocolException e){
        Log.e(LOG_TAG, "Error", e);
    }catch(IOException e){
        Log.e(LOG_TAG, "IO Error", e);
    }
    return null;
}

服务器发送给我的响应是:

    E/ScheduleRetriever: {"response":{"status":500,"message":"Intern probleem op het portal.","details":"class org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'grant_type' is not present","eventId":767369,"startRow":0,"endRow":0,"totalRows":0,"data":[]}

虽然我确实包含了POST_parameter“grant_type”。有人可以帮我弄清楚为什么服务器说它没有收到参数grant_type?

感谢。

*编辑:我使用的代码显然已过期。生成一个新的,它完全有效。谢谢!

1 个答案:

答案 0 :(得分:0)

您不应该使用func myStringErrHandler () -> (ErrorType -> String) { return { (err: ErrorType) -> (String) in switch err as! LookupError { case .CapitalNotFound: return "Couldn't find capital" case .PopulationNotFound: return "Couldn't find population" } } let errHandle = myStringErrHandler() var result = r ?? errHandle print(result) /* A-Ok */ result = d ?? errHandle print(result) /* Couldn't find capital */

覆盖Content-Type的{​​{1}} POST请求

这很可能导致服务器误解数据,因为请求的application/json应为httppost.setHeader("Content-Type", "application/json");

删除以下行,它应该有效:

Content-type