1

HttpClient(HttpComponents) を使用して HttpPost を作成しようとしています。これは私のコードです:

try{
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(
                "https://accounts.google.com/o/oauth2/token");
            post.addHeader("accept", "application/json");
            post.addHeader("Content-Type", "application/json");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("code", new String(code.getBytes(), Charset.forName("UTF-8"))));
            nvps.add(new BasicNameValuePair("client_id", "googleClientId"));
            nvps.add(new BasicNameValuePair("redirect_uri", "http://localhost:8080/myapp/test"));
            nvps.add(new BasicNameValuePair("client_secret", "ClientSecret"));
            nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
            post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));


            HttpResponse resp = httpClient.execute(post);

            if (resp.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                   + resp.getStatusLine().getStatusCode());
            }

            BufferedReader br = new BufferedReader(
                             new InputStreamReader((resp.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
                res = res + output;
            }
            System.out.println(output);
            httpClient.getConnectionManager().shutdown();
            } catch(Exception e){
                e.printStackTrace();
            }
            System.out.println(res);

コードを取得し400ます。設定したすべてのパラメーターに特殊文字が含まれているためと思われます_ . and /。エスケープされています。どうすればこれを回避できますか? それとも、本当の問題を見逃していますか?

4

1 に答える 1

1

投稿パラメーターを明示的に URL エンコードしているため、 http ヘッダー「Content-Type」はすべきapplication/x-www-form-urlencodedではありませんか?

于 2012-10-15T20:27:41.063 に答える