分享一段Android基于https协议POST数据的代码


一段Android基于https协议POST数据的代码

  1. public class HttpUtils {   
  2.     private static final String LOG_TAG = ACRA.LOG_TAG;   
  3.   
  4.     private static final TrustManager[] TRUST_MANAGER = { new NaiveTrustManager() };   
  5.   
  6.     private static final AllowAllHostnameVerifier HOSTNAME_VERIFIER = new AllowAllHostnameVerifier();   
  7.   
  8.     private static final int SOCKET_TIMEOUT = 3000;   
  9.   
  10.     /**  
  11.      * Send an HTTP(s) request with POST parameters.  
  12.      *   
  13.      * @param parameters  
  14.      * @param url  
  15.      * @throws UnsupportedEncodingException  
  16.      * @throws IOException  
  17.      * @throws KeyManagementException  
  18.      * @throws NoSuchAlgorithmException  
  19.      */  
  20.     public static void doPost(Map<?, ?> parameters, URL url, String login, String password)   
  21.             throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {   
  22.   
  23.         URLConnection cnx = getConnection(url);   
  24.   
  25.         // Construct data   
  26.         StringBuilder dataBfr = new StringBuilder();   
  27.         for (Object key : parameters.keySet()) {   
  28.             if (dataBfr.length() != 0) {   
  29.                 dataBfr.append('&');   
  30.             }   
  31.             Object value = parameters.get(key);   
  32.             if (value == null) {   
  33.                 value = "";   
  34.             }   
  35.             dataBfr.append(URLEncoder.encode(key.toString(), "UTF-8")).append('=')   
  36.                     .append(URLEncoder.encode(value.toString(), "UTF-8"));   
  37.         }   
  38.   
  39.         // Add BASIC auth credentials if available   
  40.         if (!isNull(login) || !isNull(password)) {   
  41.             String userPassword = (login != null ? login : "") + ":" + (password != null ? password : "");   
  42.             String encodedAuth = Base64.encodeToString(userPassword.getBytes(), Base64.DEFAULT);   
  43.             cnx.setRequestProperty("Authorization""Basic " + encodedAuth);   
  44.         }   
  45.         // POST data   
  46.         cnx.setDoOutput(true);   
  47.            
  48.         OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());   
  49.         Log.d(LOG_TAG, "Posting crash report data");   
  50.         wr.write(dataBfr.toString());   
  51.         wr.flush();   
  52.         wr.close();   
  53.   
  54.         Log.d(LOG_TAG, "Reading response");   
  55.         BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));   
  56.   
  57.         String line;   
  58.         int linecount = 0;   
  59.         try {   
  60.             while ((line = rd.readLine()) != null) {   
  61.                 linecount++;   
  62.                 if (linecount <= 10) {   
  63.                     Log.d(LOG_TAG, line);   
  64.                 }   
  65.             }   
  66.         } catch (Exception e) {   
  67.             Log.i(LOG_TAG, "Ignoring exception while reading result", e);   
  68.         }   
  69.         rd.close();   
  70.     }   
  71.   
  72.     private static boolean isNull(String aString) {   
  73.         return aString == null || aString == ReportsCrashes.NULL_VALUE;   
  74.     }   
  75.   
  76.     /**  
  77.      * Open an URL connection. If HTTPS, accepts any certificate even if not  
  78.      * valid, and connects to any host name.  
  79.      *   
  80.      * @param url  
  81.      *            The destination URL, HTTP or HTTPS.  
  82.      * @return The URLConnection.  
  83.      * @throws IOException  
  84.      * @throws NoSuchAlgorithmException  
  85.      * @throws KeyManagementException  
  86.      */  
  87.     private static URLConnection getConnection(URL url) throws IOException, NoSuchAlgorithmException,   
  88.             KeyManagementException {   
  89.         URLConnection conn = url.openConnection();   
  90.         if (conn instanceof HttpsURLConnection) {   
  91.             // Trust all certificates   
  92.             SSLContext context = SSLContext.getInstance("TLS");   
  93.             context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());   
  94.             SSLSocketFactory socketFactory = context.getSocketFactory();   
  95.             ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);   
  96.   
  97.             // Allow all hostnames   
  98.             ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);   
  99.   
  100.         }   
  101.         conn.setConnectTimeout(SOCKET_TIMEOUT);   
  102.         conn.setReadTimeout(SOCKET_TIMEOUT);   
  103.         return conn;   
  104.     }  

相关内容