2012-10-15 51 views
1

我想使用HttpClient(HttpComponents)做一个HttpPost。这是我的代码: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 /,它们正在越狱。我怎样才能避免这种情况?或者我错过了真正的问题?

+0

http://stackoverflow.com/questions/3286067/url-encoding-in-android – kosa

+0

@Nambari这是邮政,所以我无关的网址。 – Dragos

+0

@Nambari我错过了什么?我是否以某种方式在URL中发送参数? – Dragos

回答

1

因为您明确地对网址参数进行了URL编码,所以不应该将http头“Content-Type”设为application/x-www-form-urlencoded

+0

我编码的URL参数?他们不是在邮政体内传送的吗? – Dragos

+0

如果是这样,我该如何传输请求体中的参数? – Dragos

+0

我终于解决了。这只是问题的一部分,其余的根据这里的答案解决:http://stackoverflow.com/questions/11485271/google-oauth-2-authorization-error-redirect-uri-mismatch谢谢! – Dragos