日期:2014-05-20 浏览次数:20770 次
import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Display; class HTTPManager extends Thread{ /* * 我算是服了各个厂商,moto你干嘛这样非得再开个线程了。 * * */ private String toUrl = ""; private String Host = ""; private boolean isCMWAP = false; private String re = ""; public String getToUrl() { return toUrl; } void setToUrl(String to) { toUrl = to; } String getHost() { return Host; } void setHost(String host) { Host = host; } boolean isCMWAP() { return isCMWAP; } void setCMWAP(boolean is) { isCMWAP = is; } String getRe() { return re; } void setRe(String r) { re = r; } SinaPay getListener() { return listener; } void setListener(SinaPay lis) { listener = lis; } private Sy listener = null; public synchronized void run() { HttpConnection httpConn = null; InputStream is = null; OutputStream os = null; int cleng = 0; byte data[]= null; if(isCMWAP){ toUrl = "http://10.0.0.172:80"+toUrl; }else{ toUrl = "http://"+Host+toUrl; } System.out.println("访问:"+toUrl); try{ httpConn = (HttpConnection)Connector.open(toUrl); if(isCMWAP){ httpConn.setRequestProperty("X-Online-Host",Host); } httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestProperty("Accept", "*/*"); httpConn.setRequestMethod(HttpConnection.POST); os = httpConn.openOutputStream(); os.write("d".getBytes()); //os.flush(); os.close(); is = httpConn.openInputStream(); int respond = httpConn.getResponseCode(); if (respond != httpConn.HTTP_OK){ listener.setHttpRe(String.valueOf(respond)); listener.setDoGeting(false); return; } cleng = (int) httpConn.getLength(); if (cleng > 0) { data = new byte[cleng]; int r = is.read(data, 0, cleng); while (r < cleng) { int n = is.read(data, r, cleng-r); r += n; } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = is.read()) != -1) { baos.write(b); } data = baos.toByteArray(); } re = new String(data,"UTF-8"); System.out.println("get返回:"+re); is.close(); httpConn.close(); httpConn = null; is = null; listener.setHttpRe(re); listener.setDoGeting(false); } catch (Exception e){ //System.out.println("错误:"+e.toString()); e.printStackTrace(); listener.setHttpRe(e.toString()); listener.interp(); listener.setDoGeting(false); //throw new Exception("conn"); } finally { try { if(is != null){ is.close(); } if(httpConn != null){ httpConn.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } void doGet(String url, String cHost, boolean isCMWap,Sy lis){ this.setToUrl(url); this.setHost(cHost); this.setCMWAP(isCMWap); this.setListener(lis); Thread a = new Thread(this); a.start(); }