2013-08-12 100 views
1

我有一個谷歌的令牌,並用它,我要求從谷歌認證的URL與以下cURL命令:轉換cURL命令成純Java

curl --data 'accountType=&Email=&has_permission=1&Token= + $$TOKEN$$ + &service=weblogin%3Acontinue%3Dhttps%253A//www.google.com/dashboard/&source=&androidId=&app=&client_sig=&device_country=&operatorCountry=&lang=&RefreshServices=' -k 'https://android.clients.google.com/auth' 

我如何轉換該命令爲純java命令與URL連接或Apache HTTP庫?這樣我就不必再使用cURL二進制。

我看到了幾個例子,但我面臨POST參數的一些麻煩。我無法得到是正確的。

我的Java嘗試:

$$ TOKEN $$ - >必須由真正的令牌替換。

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

public class Test implements Runnable { 

    public static void main(String args[]) { 
     new Test(); 
    } 

    public Test() { 
     Thread thread = new Thread(this); 
     thread.start(); 
    } 

    @Override 
    public void run() { 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost("https://android.clients.google.com/auth"); 

     try { 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      nameValuePairs.add(new BasicNameValuePair("accountType", "")); 
      nameValuePairs.add(new BasicNameValuePair("Email", "")); 
      nameValuePairs.add(new BasicNameValuePair("has_permission", "1")); 
      nameValuePairs.add(new BasicNameValuePair("Token", "$$ TOKEN $$")); 
      nameValuePairs.add(new BasicNameValuePair("service", "weblogin%3Acontinue%3Dhttps%253A//www.google.com/dashboard/")); 
      nameValuePairs.add(new BasicNameValuePair("androidId", "")); 
      nameValuePairs.add(new BasicNameValuePair("app", "")); 
      nameValuePairs.add(new BasicNameValuePair("client_sig", "")); 
      nameValuePairs.add(new BasicNameValuePair("device_country", "")); 
      nameValuePairs.add(new BasicNameValuePair("operatorCountry", "")); 
      nameValuePairs.add(new BasicNameValuePair("lang", "")); 
      nameValuePairs.add(new BasicNameValuePair("RefreshServices", "")); 

      post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = client.execute(post); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

      String line = ""; 
      while ((line = rd.readLine()) != null) { 
      System.out.println(line); 

      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我的Eclipse控制檯打印:

Url=https://www.google.com/accounts/ErrorMsg?id=unknown 
Error=Unknown 

SOLUTION:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.security.SecureRandom; 
import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 

import javax.net.ssl.HostnameVerifier; 
import javax.net.ssl.HttpsURLConnection; 
import javax.net.ssl.SSLContext; 
import javax.net.ssl.SSLSession; 
import javax.net.ssl.TrustManager; 
import javax.net.ssl.X509TrustManager; 

public class Test implements Runnable { 

    public static void main(String args[]) { 
     new Test(); 
    } 

    public Test() { 
     Thread thread = new Thread(this); 
     thread.start(); 
    } 

    @Override 
    public void run() { 
     String data; 
     String selectedToken = "xxx YOUR TOKEN HERE xxx"; 

     try { 
      data = "accountType=&Email=&has_permission=1&Token=" + selectedToken + 
        "&service=weblogin%3Acontinue%3Dhttps%253A//www.google.com/dashboard/&source=&androidId=" + 
        "&app=&client_sig=&device_country=&operatorCountry=&lang=&RefreshServices="; 

      // Disable cert validation 
      disableCertificateValidation(); 

      HttpURLConnection con = (HttpURLConnection) new URL("https://android.clients.google.com/auth").openConnection(); 
      con.setRequestMethod("POST"); 
      con.setDoOutput(true); 
      con.getOutputStream().write(data.getBytes("UTF-8")); 

      // Get the inputstream 
      BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); 

      // .. and print it 
      String tmp; 
      while((tmp = reader.readLine()) != null) { 
       System.out.println(tmp); 
      } 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void disableCertificateValidation() { 
     // Create a trust manager that does not validate certificate chains 
     TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { 
      public X509Certificate[] getAcceptedIssuers() { 
       return new X509Certificate[0]; 
      } 

      @Override 
      public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 

      } 

      @Override 
      public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 

      } 
     }}; 

     // Ignore differences between given hostname and certificate hostname 
     HostnameVerifier hv = new HostnameVerifier() { 
      @Override 
      public boolean verify(String hostname, SSLSession session) { 
       return true; 
      } 
     }; 

     // Install the all-trusting trust manager 
     try { 
      SSLContext sc = SSLContext.getInstance("SSL"); 
      sc.init(null, trustAllCerts, new SecureRandom()); 
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 
      HttpsURLConnection.setDefaultHostnameVerifier(hv); 
     } catch (Exception e) { 
      // Do nothing 
     } 
    } 
} 

我不得不添加SSL證書驗證,然後它的工作。

+1

發佈您的代碼和錯誤請 – Satya

+1

是否有你沒有使用OAuth庫來處理這一切的原因? – chrylis

+0

我把它編輯成第一篇文章。 –

回答

1

如果您使用java.net.HttpURLConnection,則可以將發佈數據的字節寫入輸出流。所以你所要做的就是把你的--data轉換成字節並寫入流中。

+0

我得到一個「javax.net.ssl.SSLHandshakeException」和一個「java.security.cert.CertificateException」。我怎樣才能繞過SSL證書檢查 - 就像cURL的「-k」選項一樣? –

+0

如果目標網址爲http,那麼您的答案將會像charme一樣工作。如果該網站具有SSL,則需要添加一個ssl證書驗證(請參閱我的第一篇文章中的代碼) - 然後它完美地工作。謝謝 ;) –