//引用要注意。1.android 中不允许访问网络占用住线程所以要在线程中运行2.如果你是本地电脑调试ip 为10.0.2.2,因为android 虚拟机中本地地址是这个不是127.0.0.1
new Thread(){
@Override
public void run()
{
//这里放你的那段访问网络的代码
//代码执行完毕后给handler发送消息
COMPublicclass com=new COMPublicclass();
HashMap<String, String> hm=new HashMap<String, String>();
hm.put("name", "潘立涛");
hm.put("Ename", "panlitao");
hm.put("age", "25");
String mg=com.posthtml("http://10.0.2.2:8006/WebForm9.aspx", hm);
Bundle bundle = new Bundle();
/*字符、字符串、布尔、字节数组、浮点数等等,都可以传*/
bundle.putString("gethtml", mg);
Message mag=new Message();
mag.setData(bundle);
handler.sendMessage(mag);
}
}.start();
//定义Handler对象接受返回的值
private Handler handler =new Handler(){
@Override
//当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg){
super.handleMessage(msg);
//处理UI
Bundle bundle= msg.getData();
String s= bundle.getString("gethtml");
//gethtmlcode
TextView tex= (TextView) findViewById(R.id.gethtmlcode);
tex.setText(tex.getText()+"*"+s);
}
};
//COMPublicclass 类的名称
public String posthtml(String postpath,Map<String, String> params)
{String htmlcode="";
URL url=null;
HttpURLConnection httpcon=null;
try {
url=new URL(postpath);
httpcon=(HttpURLConnection) url.openConnection();
httpcon.setDoInput(true);
httpcon.setDoOutput(true);
httpcon.setRequestMethod("POST");
httpcon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String postdata="";
//组织post参数
for(Entry<String,String> entry:params.entrySet())
postdata+= entry.getKey()+"="+entry.getValue()+"&";
byte[] entitydata = postdata.getBytes();
httpcon.setRequestProperty("Content-Length", String.valueOf(entitydata.length)); //传递数据的长据 postdata=postdata.substring(postdata.length());
//发送信息
OutputStream outStream = httpcon.getOutputStream();
outStream.write(entitydata);
outStream.flush();
outStream.close();
//
int code = httpcon.getResponseCode();
if(code==200)
{
BufferedReader reader = new BufferedReader( new InputStreamReader(
httpcon.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
//获取信息
while ((line = reader.readLine()) != null)
builder.append(line);
htmlcode = builder.toString();
reader.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (httpcon != null) {
httpcon.disconnect();
}
}
return htmlcode;
}