天天看点

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,如需转载请自行联系原作者