android url带参数传递,android平台通过http post方式向远程URL传递参数并获取返回数据...

一、开发前准备

1、在eclipse中新建一个android app工程

2、打开工程的AndroidManifest.xml文件,加上

android:name="android.permission.INTERNET" />

表示可以访问网络,并将android:minSdkVersion 设置为"11"

3、在主程序进行操作前加上以下代码

StrictMode.setThreadPolicy(new

StrictMode.ThreadPolicy.Builder()

.detectDiskReads()

.detectDiskWrites()

.detectNetwork()

.penaltyLog()

.build());

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()

.detectLeakedSqlLiteObjects()

.detectLeakedClosableObjects()

.penaltyLog()

.penaltyDeath()

.build());

主要原因是,android4.0以后的版本不允许在主程序中进行联网操作,否则会报如下错误

android.os.NetWorkOnMainException和android.os.NetWorkOnMainThreadException

二、程序中实现

String

httpUrl="要访问的http url地址";

String

resultData="";

URL

url=null;

try{

url=new

URL(httpUrl);

}

catch(MalformedURLException

e){

System.out.println(e.getMessage());

}

if(url!=null){

try{

HttpURLConnection

urlConn=(HttpURLConnection)url.openConnection();

urlConn.setDoOutput(true);

urlConn.setDoInput(true);

urlConn.setRequestMethod("POST");

urlConn.setUseCaches(false);

urlConn.setInstanceFollowRedirects(true);

urlConn.setRequestProperty("contentType",

"GBK");//解决中文显示乱码问题 urlConn.connect();

DataOutputStream

out=new DataOutputStream(urlConn.getOutputStream());

String

content="POST参数名="+URLEncoder.encode("传入值","gb2312");

out.writeBytes(content);

out.flush();

out.close();

BufferedReader

reader=new BufferedReader(new

InputStreamReader(urlConn.getInputStream(),"GBK"));

String

inputLine=null;

while((inputLine=reader.readLine())!=null){

resultData+=inputLine+"\n";

}

reader.close();

urlConn.disconnect();

if(resultData!=""){

System.out.println(resultData);

}else{

System.out.println("Sorry,the

content is null");

}

}

catch(IOException

e){

System.out.println(e.getMessage());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值