13,100
社区成员
发帖
与我相关
我的任务
分享
String url = "http://localhost:8080/mail/mobile.do";
String parameters = "method=sendmail&receivers=" + Receivers.getText() + "&theme=" + Theme.getText() + "&content=" + ta.getText();
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
/**
* 本线程用于联网取数据
* @author Silence
*/
public class HttpRequest implements Runnable {
private String url = null;
private String parameters = null;
private String result = null;
private CallBack cb = null;
private HttpConnection hc = null;
private InputStream is = null;
private OutputStream os = null;
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
static String sid=null; //session id
public HttpRequest(String url, String parameters, CallBack cb) {
this.url = url;
this.parameters = parameters;
this.cb = cb;
}
public void run() {
try {
hc = (HttpConnection) Connector.open(url);
hc.setRequestMethod(HttpConnection.POST);
if(sid!=null){ //提交sessionId
hc.setRequestProperty("Cookie", sid);
}
hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = hc.openOutputStream();
os.write(parameters.getBytes());
if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
is = hc.openInputStream();
String cookie=hc.getHeaderField("Set-cookie"); //获取响应中的sessionId
if(cookie!=null){
sid=cookie.substring(0, cookie.indexOf(";"));
System.out.println("SessionId:"+sid);
}
byte[] data = null;
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
data = baos.toByteArray();
result=new HGB2312().gb2utf8(data); //将GB2312转成UTF-8显示
System.out.println("result:"+result);
cb.CallBack(result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
baos.close();
baos=null;
is.close();
is=null;
os.close();
os=null;
hc.close();
hc=null;
} catch (Exception e) {
}
}
}
}
os = hc.openOutputStream();
dos.write(parameters.getBytes("UTF-8"));//根据需要自己改
os = hc.openOutputStream();
dos.write(parameters.getBytes("UTF-8"));//根据需要自己改