android 后台post 数据

//引用要注意。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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值