2012年9月25日 星期二

Android 用post傳送資料


String ServerAddress = "http://192.168.0.1";
String DataA = "1";
String DataB = "2";
String result = "";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("AA",DataA ));
params.add(new BasicNameValuePair("BB",DataB ));


HttpPost httpRequest = new HttpPost(ServerAddress);
try {
    httpRequest.setEntity(new UrlEncodedFormEntity(getParams(),HTTP.UTF_8));
    HttpResponse mHttpResponse = new DefaultHttpClient().execute(httpRequest);
    
    if(mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
        result = EntityUtils.toString(mHttpResponse.getEntity());    
    }
    
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}


宣告一個 List<NameValuePair> 這裡面是等一下要放入要傳的值及傳的名稱
List<NameValuePair> params = new ArrayList<NameValuePair>();

接下來設定傳入名稱及資料,在這裡是傳AA的名稱,DataA是我們的資料

params.add(new BasicNameValuePair("AA",DataA ));


有幾個就以此類推


接著下面是回傳的結果

if(mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
     result = EntityUtils.toString(mHttpResponse.getEntity());    
}



可以參考下面檔案

https://www.dropbox.com/s/uxzhtg3roeqwycm/ServerRequest.7z






Java - MD5


public static String md5Encode(String str) {
    StringBuffer buf = new StringBuffer();
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(str.getBytes());
        byte bytes[] = md5.digest();
        for(int i = 0; i < bytes.length; i++) {
            String s = Integer.toHexString(bytes[i] & 0xff);
            if(s.length()==1) {
                buf.append("0");
            }
            buf.append(s);
        }

    } catch(Exception ex) {
        
    }
    return buf.toString();
}