⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httptest.java

📁 J2ME MIDP 2.0 无线设备编程的一些源码
💻 JAVA
字号:
//HttpTest.java
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HttpTest extends MIDlet implements CommandListener
{
    //命令对象
    private Command exitCommand, streamCmd, contentCmd, httpCmd,httpPostCmd;
    private TextBox tb; //通过TextBox来显示信息
    private Ticker tker; //访问网络时显示滚动的标题
    public HttpTest()
    {
        tb =new TextBox("URL","http://localhost/j2me.asp",120,TextField.ANY);
        tker = new Ticker("Loading");
        exitCommand =new Command("Exit",Command.EXIT,1);
        streamCmd =new Command("StreamConnectTest",Command.SCREEN,1);
        contentCmd =new Command("ContentConnectionTest",Command.SCREEN,1);
        httpCmd =new Command("HttpConnectionTest",Command.SCREEN,1);
        httpPostCmd =new Command("HttpPost",Command.SCREEN,1);
        tb.addCommand(exitCommand);
        tb.addCommand(streamCmd);
        tb.addCommand(contentCmd);
        tb.addCommand(httpCmd);
        tb.addCommand(httpPostCmd);
        tb.setCommandListener(this);
    }
    protected void startApp(  ) throws MIDletStateChangeException
    {
        Display.getDisplay(this).setCurrent(tb);
    }

    protected void pauseApp(  )
    {
    }

    protected void destroyApp( boolean p1 )
    {
    }

    public void commandAction(Command c,Displayable d)
    {
        if (c ==exitCommand)
        {
            destroyApp(false);
            notifyDestroyed();
        }
        else if(c ==streamCmd)
        {
            tb.setTicker(tker);
            new Tester(tb, 0, tb.getString());
        }
        else if(c ==contentCmd)
        {
            tb.setTicker(tker);
            new Tester(tb, 1, tb.getString());
        }
        else if(c ==httpCmd)
        {
            tb.setTicker(tker);
            new Tester(tb, 2, tb.getString());
        }
        else if(c ==httpPostCmd)
        {
            tb.setTicker(tker);
            new Tester(tb, 3, tb.getString());
        }
    }
class Tester extends Thread
{
    private int testType;
    private String testUrl;
    private TextBox textBox;
    public Tester(TextBox tb, int type,String url)
    {
        textBox = tb;
        testType = type;
        testUrl = url;
        this.start();
    }
    public void run()
    {
        try 
        {
            switch(testType)
            {//使用四种方式进行HTTP 访问
                case 0:
                    getViaStreamConnection(testUrl);
                break;
                case 1:
                    getViaContentConnection(testUrl);
                break;
                case 2:
                    getViaHttpConnection(testUrl);
                break;
                case 3:
                    getViaHttpConnectionPost(testUrl,"username=XXXX&password=YYYY");
                break;
            }
        }
        catch(Exception e)
        {System.out.println("error = "+e.getMessage());}   
        textBox.setTicker(null);
    }
    public void getViaStreamConnection(String url) throws IOException
    {//通过 StreamConnection 对象来读取网页内容
        StringBuffer strbuf=new StringBuffer(); //保存读入的字符
        StreamConnection c = null;
        InputStream s = null;
        try 
        {
            c = (StreamConnection)Connector.open(url); //打开对象
            s = c.openInputStream(); //转换到Connected 状态
            int ch;
            while ((ch = s.read()) != -1) 
            {//逐个读入字节数据
                strbuf.append((char)ch);
            }
        }
        catch(IOException e)
        { System.out.println("error = "+e.getMessage()); }
        finally
        {
            System.out.println("content = " + strbuf.toString());//跟踪输入读入的数据
            strbuf = null;
            if(s != null)
                s.close();
            if(c != null)
                c.close();
         }
    }

    void getViaContentConnection(String url) throws IOException
    {//通过 ContentConnection 对象来获取网页内容
        StringBuffer strbuf=new StringBuffer();
        ContentConnection c = null;
        DataInputStream dis = null;
        try 
        {
            c = (ContentConnection)Connector.open(url); //打开对象
            int len = (int)c.getLength();
            dis = c.openDataInputStream(); //转换到Connected 状态
            if (len > 0) 
            {//如果服务器通过 Content-Length 属性返回了长度则读入全部数据
                byte[] data = new byte[len];
                dis.readFully(data);
                System.out.println("Content-Length:" + len);
                for(int i=0;i<data.length;i++)
                    strbuf.append((char)data[i]);//把数据添加到StringBuffer对象中
            } 
            else
            {//否则逐个字节读入
                int ch;
                while ((ch = dis.read()) != -1) 
                    strbuf.append((char)ch);
            }
        } 
        catch(IOException e)
        { System.out.println(e.getMessage()); }
        finally 
        {
            System.out.println("content = " + strbuf.toString());//跟踪输入读入的数据
            strbuf = null;
            if (dis != null)
                dis.close();
            if (c != null)
                 c.close();
        }
    }
    
    public void getViaHttpConnection(String url) throws IOException 
    {//通过 HttpConnection 对象来获取网页内容
        StringBuffer strbuf=new StringBuffer(); //保存读入的字符
        HttpConnection  c = null;
        InputStream is  = null;
        try
        {
            c = (HttpConnection)Connector.open(url); //创建 HttpConnection 对象
            c.setRequestProperty("User-Agent","MIDP/2.0");//设置客户方名称
            c.setRequestProperty("Accept","text/html, text/plain, text/xml, image/png, */*");//设置可接受的MIME类型
            
            //跟踪输出
            System.out.println("Method = " +c.getRequestMethod());
            System.out.println("URL = " +c.getURL());
            System.out.println("Protocol= " +c.getProtocol());
            System.out.println("Host = " +c.getHost());
            System.out.println("Port = " +c.getPort());
            System.out.println("File = " +c.getFile());
            System.out.println("QueryString = " +c.getQuery());
            
            int rc  = c.getResponseCode(); //转换到Connected 状态
            System.out.println("ResponseCode = "+rc);
            System.out.println("ResponseMessage = "+c.getResponseMessage());
            //输出头信息中的各种属性
            String key;
            for(int i=0;null !=(key=c.getHeaderFieldKey(i));i++)
            {
                System.out.println(key +" = "+ c.getHeaderField(i));
            }
            is  = c.openInputStream();//打开输入流
            int len = (int)c.getLength();
            if(len > 0) 
            {
                int ch;
                for(int i=0;i<len && (ch=is.read())!=-1 ;i++)
                {//逐个读入数据,也可以利用 InputStream 的其他 read 方法一次读入多个字节
                    strbuf.append((char)ch);
                }
            } 
            else
            {
                int ch;
                while ((ch = is.read()) != -1) 
                    strbuf.append((char)ch);
            }
        }
        catch (IOException e) 
        {
            System.out.println("error = "+e.getMessage()); 
        }
        finally
        {
            System.out.println("content = " + strbuf.toString());//跟踪输入读入的数据
            strbuf = null;
            if (is != null)
                is.close();
            if (c != null)
                c.close();
        }
    }
    public void getViaHttpConnectionPost(String url, String param) throws IOException 
    {//通过 HttpConnection 对象的POST 方法来获取网页内容
        StringBuffer strbuf=new StringBuffer(); //保存读入的字符
        HttpConnection  c = null;
        InputStream is  = null;
        OutputStream os = null;

        try
        {
            c = (HttpConnection)Connector.open(url); //创建 HttpConnection 对象
            c.setRequestMethod(HttpConnection.POST);
            strbuf.append(param.length());
            c.setRequestProperty("Content-Length",strbuf.toString());//设置参数长度
            c.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//设置参数MIME类型
            strbuf.delete(0,strbuf.length());
            
            os = c.openOutputStream(); //得到输出流对象
            os.write(param.getBytes());
            
            int rc  = c.getResponseCode(); //转换到Connected 状态
            System.out.println("ResponseCode = "+rc + " "+c.getResponseMessage());
            is  = c.openInputStream();//打开输入流
            int len = (int)c.getLength();
            if(len > 0)
            {
                int ch;
                for(int i=0;i<len && (ch=is.read())!=-1 ;i++)
                {//逐个读入数据,也可以利用 InputStream 的其他 read 方法一次读入多个字节
                    strbuf.append((char)ch);
                }
            }
            else
            {
                int ch;
                while ((ch = is.read()) != -1) 
                    strbuf.append((char)ch);
            }
        }
        catch (IOException e) 
        { System.out.println("error = "+e.getMessage()); }
        finally
        {
            System.out.println("content = " + strbuf.toString());//跟踪输入读入的数据
            strbuf = null;
            if (is != null)
                is.close();
            if (c != null)
                c.close();
        }
    }
}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -