1、檢測網絡狀态的代碼
connectivitymanager cm = (connectivitymanager) context.getsystemservice(context.connectivity_service);
networkinfo netinfo = cm.getactivitynetworkinfo();
netinfo.tostring();
2.使用網絡權限
<uses-permission android:name="android.permission.internet"/>
3.通過url + httpurlconnection獲得資料(文本和圖檔)
url url = new url("http://www.sohu.com");
httpurlconnection conn = (httpurlconnectioni) url.openconnection();
conn.setconnectiontimeout(5*1000);
conn.setrequestmethod("get");
conn.getresponsemethod("get");
(conn.getresponsecode() != 200 ) throw...;
inputstream is = conn.getinputstream();
string result = readdata(is,"gek");
conn.disconnect();
//擷取圖檔同上
1.get方式發送name-value對
//http://xxxx/xxx.action?name=tom&&age=12
url realurl = new url(requesturl);
httpurlconnection conn = (httpurlconnection) realurl.openconnection();
conn.setconnectiontimeout(5000);
//直到此時,資料才發往伺服器
if( conn.getresponsecode() == 200 ){
string result = readasstring(conn.getinputstream(), "utf-8");
outstream.close();
system.out.println(result);
}
注:中文亂碼問題.
//utf-8指伺服器端編碼
1.get方式發送中文需要轉碼.urlencode("中文","utf-8");
2.tomcat器端需要轉碼(get方式).
if("get".equals(request.getmethod())){
string v =request.getparameter("name");
new string(v.getbytes("iso8859-1"),"utf-8");
1.post發送普通文本内容
httpurlconncection conn = (httpurlconnection) realurl.openconnection();
conn.setdooutput(true);
conn.setusecaches(false);
conn.setrequestmethod();
conn.setrequestproperty("connection","keep-alive");//維持長連接配接
conn.setrequestproperty("charset","utf-8");
con.setrequestproperty("content-length", string.valueof(data.length));
con.setrequestproperty("content-type","application/x-www-form-urlencoded");
string str = "name=xxx&age=12";
con.getoutputstream().write(str.getbytes);
if(conn.getoutputstream().write(str.getbytes)){
if(conn.getresponsecode()==200){
string result = readasstring(conn.getinputstream(),"utf-8");
system.out.println(result):
1.post發送xml
stringbuilder xml = new stringbuilder();
xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
xml.append("<m1 v=10000>");
xml.append("<u i=1 d=\"n73\">中國</u>");
xml.append("</m1>");
byte[] xmlbyte = xml.tostring().getbytes("utf-8");
url url = new url("http://xxx.do?method=readxml");
httpurlconnection conn = (httpurlconnection) url.openconnection();
conn.setconnecttimeout(5* 1000);
conn.setdooutput(true);//允許輸出
conn.setusecaches(false);//不使用cache
conn.setrequestmethod("post");
conn.setrequestproperty("connection", "keep-alive");//維持長連接配接
conn.setrequestproperty("charset", "utf-8");
conn.setrequestproperty("content-length", string.valueof(xmlbyte.length));
//必須設定内容類型,否則伺服器無法識别資料類型.
conn.setrequestproperty("content-type", "text/xml; charset=utf-8");
dataoutputstream outstream = new dataoutputstream(conn.getoutputstream());
outstream.write(xmlbyte);//發送xml資料
outstream.flush();