2012-10-15 92 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