天天看點

android實用的代碼

今天晚上寫了測試類,雖然說達不到什麼效果。但是能給大家一些實用的代碼。

讓我看看代碼的:

package com.smart.net.utils;  

import java.io.ByteArrayOutputStream;  

import java.io.DataOutputStream;  

import java.io.File;  

import java.io.FileOutputStream;  

import java.io.InputStream;  

import java.net.HttpURLConnection;  

import java.net.URL;  

import java.net.URLEncoder;  

import java.util.Map;  

public class NetTool {  

    /**  

     * byte[] data=param.getBytes(); 以後要注意,發送資料接收資料,都要用位元組數組去接收它  

     *   

     * Content-Type 指action entype="multipart/x-"  

     * */ 

    public static InputStream sendPostRequest(String uriPath,  

            Map<String, String> params, String encoding) throws Exception {  

        // String param="id=67&name"+URLEncoder.encode("老梁","UTF-8");//要發送的資料  

        StringBuilder sb = new StringBuilder();  

        // 進行封裝  

        for (Map.Entry<String, String> entry : params.entrySet()) {  

            sb.append(entry.getKey()).append("=")  

                    .append(URLEncoder.encode(entry.getValue(), encoding));  

            sb.append('&');  

        }  

        sb.deleteCharAt(sb.length() - 1);  

        byte[] data = sb.toString().getBytes();  

        URL url = new URL(uriPath);  

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  

        conn.setConnectTimeout(6 * 1000);  

        conn.setDoOutput(true);// 發送POST至伺服器  

        conn.setUseCaches(false);  

        conn.setRequestMethod("POST");  

        conn.setRequestProperty("Connection", "Keep-Alive");  

        conn.setRequestProperty("Charset", "UTF-8");  

        conn.setRequestProperty("Content-Length", String.valueOf(data.length));  

        conn.setRequestProperty("Content-Type",  

                "application/x-www-form-urlencoded");  

        DataOutputStream dataOutStream = new DataOutputStream(  

                conn.getOutputStream());// 得到輸出流  

        dataOutStream.write(data);  

        dataOutStream.flush();  

        dataOutStream.close();  

        System.out.println(conn.getResponseCode());  

        if (conn.getResponseCode() == 200) {  

            return conn.getInputStream();  

        return null;  

    }  

    public static String getTextContent(InputStream inStream,String encoding) throws Exception {  

            byte[] data=readStream(inStream);  

            return new String(data,encoding);  

     * 擷取URL路徑指定的内容  

     * 獲得指定内容  

    public static String getTextContent2(String path,String encoding) throws Exception {  

        URL url = new URL(path);  

        conn.setRequestMethod("GET");  

        // 别超過10秒。  

        if(conn.getResponseCode()==200){  

            InputStream inputStream=conn.getInputStream();  

            byte[] data=readStream(inputStream);  

     * 直接可以得到文本與流的資料  

    public static InputStream getContent(String uriPath) throws Exception {  

//  /**  

//   * 直接可以得到文本與流的資料  

//   * */  

    public static InputStream getContentImputStream(String path,String encoding) throws Exception {  

/**  

 * 擷取指定路徑,的資料。  

 *   

 * **/ 

    public static byte[] getImage(String urlpath) throws Exception {  

        URL url = new URL(urlpath);  

            return readStream(inputStream);  

     * 讀取資料   

     * 輸入流  

    public static byte[] readStream(InputStream inStream) throws Exception {  

        ByteArrayOutputStream outstream=new ByteArrayOutputStream();  

        byte[] buffer=new byte[1024];  

        int len=-1;  

        while((len=inStream.read(buffer)) !=-1){  

            outstream.write(buffer, 0, len);  

        outstream.close();  

        inStream.close();  

    return outstream.toByteArray();  

}  

package com.smart.activity;  

import java.io.FileInputStream;  

import java.util.ArrayList;  

import java.util.HashMap;  

import java.util.List;  

import org.apache.http.HttpResponse;  

import org.apache.http.NameValuePair;  

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;  

import org.apache.http.protocol.HTTP;  

import android.test.AndroidTestCase;  

import android.util.Log;  

import com.smart.net.utils.FormFile;  

import com.smart.net.utils.HttpRequester;  

import com.smart.net.utils.NetTool;  

 * 如何使用大資料發送  

 * */ 

public class PostParamTest extends AndroidTestCase {  

    /***  

     * 本代碼報錯,原因為資料類型不對,18 向Internet上傳檔案-1.avi  38:38分  

    private final String TAG = "PostParamTest";  

/***  

 * 上專檔案,  

 * 要有四部份資料  

 * 名稱  

 * 内容類型  

 * 表單字段名稱  

 * 類型  

 * 發送檔案及文本請求參數  

 * 面試上專100M  

 * 檔案讀成數組,然後寫上傳上去  

 *上傳到網絡流裡面去,   

    //發送檔案及文本請求參數  

    public void testSendPostFileparams() throws Exception{  

        Map<String,String> params=new HashMap<String,String>();  

        params.put("method", "save");  

        params.put("id", "988");  

        params.put("name", "老梁");  

        FileInputStream inStream=new FileInputStream(new File("/sdcard/smart.xml"));  

//      byte[] data=NetTool.readStream(inStream);  

//      inStream.close();  

        FormFile file=new FormFile("smart.xml",inStream,"file","test/xml");  

        //這行代碼出現報錯  

//      HttpRequester.post("www.baidu.com",params,file);  

//      HttpRequester.post("", params, null);  

     * 利用  

     * (資源包)httpcomponents-asyncclient-4.0根據包下面的内容顯示,  

     * pairms.add(new BasicNameValuePair("id", "988"));//伺服器端  

        pairms.add(new BasicNameValuePair("name", "老梁"));  

        pairms.add(new BasicNameValuePair("method", "save"));  

     * 兩種做方法  

    //通過HhttpClien發送Post請求  

    public void testSendPostParamFromHttpClient() throws Exception {  

        HttpPost httpPost = new HttpPost("");//請求參數,指伺服器位址。  

        List<NameValuePair> pairms = new ArrayList<NameValuePair>();//參婁  

        pairms.add(new BasicNameValuePair("id", "988"));//伺服器端  

        //代表資料部分  

        httpPost.setEntity(new UrlEncodedFormEntity(pairms, HTTP.UTF_8));  

        DefaultHttpClient httpclient = new DefaultHttpClient();  

        HttpResponse response = httpclient.execute(httpPost);  

        response.getEntity().getContent();  

        // Log.i(TAG, result);  

    // 讀取伺服器資訊  

//自定義發送Post請求  

    public void testSendPostParam() throws Exception {  

        // 這裡放的伺服器位址,我們可以把JAVA寫的項目眼布起來,一樣都可以使用。  

        String path = "http:www.baidu.com";  

        Map<String, String> params = new HashMap<String, String>();  

        params.put("methos", "save");  

        params.put("id", "29832");  

        String result = NetTool.getTextContent(NetTool.sendPostRequest(path,params,"UTF-8"), "UTF-8");  

        Log.i(TAG, result);  

import java.io.ByteArrayInputStream;  

import java.io.OutputStreamWriter;  

import android.os.Environment;  

import com.smart.domain.Resource;  

import com.smart.net.utils.SAXResourceService;  

public class GetXMLTest extends AndroidTestCase {  

    private static final String TAG = "GetXMLTest";  

    public void testGetXML() throws Exception {  

        // 如果參數是中文,必須進行Url編碼  

        String path = "http://211.143.108.6/wap/ResCatService?act=pic&s=h";  

//      String xml = NetTool.getTextContent(NetTool.getContent(path), "UTF-8");  

        String xml = NetTool.getTextContent2(path, "UTF-8");  

        FileOutputStream outStream=new FileOutputStream(new File(Environment.getExternalStorageDirectory(),"test.xml"));  

        OutputStreamWriter writer=new OutputStreamWriter(outStream,"UTF-8");  

        writer.write(xml);  

        writer.flush();//一定寫進這個方法,要不然,寫到内容裡面就會沒有寫入文本  

        outStream.close();  

//      Log.i(TAG, xml);  

    //這種性能會差一點  

    public void testGetXMLAndParser() throws Exception {  

        // 如果參數是中文,必須進行URI編碼  

        String xml = NetTool.getTextContent(NetTool.getContent(path), "UTF-8");  

        InputStream inStream=new ByteArrayInputStream(xml.getBytes());  

        Resource resource=SAXResourceService.readXml(inStream);  

        Log.i(TAG, resource.toString());//列印出來XML檔案的資源  

//  public void testGetXMLAndParset() throws Exception{  

//      String path="";  

//      String xml=Net  

//  }  

    //這種調用方法效果相對來講會好一點  

    public void testGetXMLAndParser2() throws Exception {  

        InputStream inStream = NetTool.getContent(path);//  

//      InputStream inStream=new ByteArrayInputStream(xml.getBytes());  

        if(inStream!=null){  

            Resource resource=SAXResourceService.readXml(inStream);  

            Log.i(TAG, resource.toString());//列印出來XML檔案的資源  

        }else{  

            Log.i(TAG, "----------->ERROR");  

本文轉自 llb988 51CTO部落格,原文連結:http://blog.51cto.com/llb988/512847,如需轉載請自行聯系原作者