weatherreader.java

来自「《J2ME实用教程》清华大学出版社出版」· Java 代码 · 共 51 行

JAVA
51
字号
package com.j2medev.chapter4;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.Form;

public class WeatherReader implements Runnable{
    
    private WeatherMIDlet midlet;
    private String param;
    public static final String host = "http://localhost:8080/yahooweather/weather?";
    
    public WeatherReader(WeatherMIDlet midlet,String param) {
        this.midlet = midlet;
        this.param = param;
    }
    
    public void run(){
        HttpConnection conn = null;
        try{
            WaitingForm wait = new WaitingForm();
            midlet.setCurrent(wait);
            wait.update();
            conn = (HttpConnection)Connector.open(host+param);
            conn.setRequestMethod(HttpConnection.GET);
            int responseCode = conn.getResponseCode();
            wait.update();
            if(responseCode != HttpConnection.HTTP_OK){
                //简单起见,只要返回码不等于200则抛出异常
                throw new IOException("Can't connect to server");
            }
            DataInputStream dis = conn.openDataInputStream();
            String result = dis.readUTF();
            wait.update();
            midlet.displayWeather(result);
        }catch(IOException ex){
            //出错提示信息
            Form form = new Form("error");
            form.append(ex.getMessage());
            midlet.setCurrent(form);
        }finally{
            try{
                if(conn != null)
                    conn.close();
            }catch(IOException e){
                
            }
        }
    }
}

⌨️ 快捷键说明

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