【问题标题】:cUrl HttpPost parameters not recognized(?) by server服务器无法识别 cUrl HttpPost 参数(?)
【发布时间】:2016-01-03 00:52:44
【问题描述】:

我正在尝试从服务器获取授权密钥。在文档中,他们声明我可以通过执行以下 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?

谢谢。

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

【问题讨论】:

    标签: android json post curl httpclient


    【解决方案1】:

    您不应使用 httppost.setHeader("Content-Type", "application/json"); 行将 POST 请求的 Content-Type 覆盖为 application/json

    这很可能导致服务器误解数据,因为请求的Content-type 应该是application/x-www-form-urlencoded

    删除以下行,它应该可以工作:

    httppost.setHeader("Content-Type", "application/json");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多