一、开发前准备
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());
}
}