天天看点

Android互联网访问,get方式,post方式等方式

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();

继续阅读