-
HttpURLConnection接口
需要在AndroidManifest.xml添加
<uses-permission android:name="android.permission.INTERNET"/>
还可以用过HttpURLConnection句柄设置对应的属性(连接)
代码:
GET:
/设置/url
String httpUrl = "http://10.0.2.2/****" ;
//get data
String result = "";
Url url = null
try{
//构造url对象
url = new URL(httpUrl);
}catche(MalformedException e){ Log.e(DEBUG_TAG,"MalformedException")}
if(url !=null){
try{
//使用HttpURLConnection并打开连接
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//读取得到的内容(流)
InputStreamReader in = new InpurStreamReader(urlConn.getInputStream());
//创建bufferreader
BufferReader buffer = new BufferedReader(in);
//
String inputLine = null;
//循环获取得到数据
while((inputLine = buffer.readLine())!=null){
//
result += inputLine+"\n";
}
//关闭输入流
in.close();
//关闭连接
urlConn.close();
//处理数据..................
}catche(IOException e){Log.e(DEBUG_TAG,"IOException")}
}
POST
/设置/url
String httpUrl = "http://10.0.2.2/****" ;
//get data
String result = "";
Url url = null
try{
//构造url对象
url = new URL(httpUrl);
}catche(MalformedException e){ Log.e(DEBUG_TAG,"MalformedException")}
if(url !=null){
try{
//使用HttpURLConnection并打开连接
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//设置post方式需要设置下面
urlConn.setDoOutput(true);urlConn.setDoInput(true);
//设置post请求
urlConn.setRequestMethod("POST");
//post请求不能使用cache
urlConn.setUseCache(false);urlConn.setInstanceFollowRedirects(true);
//配置本次连接
urlConn.setRequestProperty("ContentType","application/x-www-form-urlencode");
//连接,从打开到此之前的配置需要全部完成。需要注意的是在connection.getOutputStream();时候会隐含进行connection
urlConn.connection();
//读取得到的内容(流)
DataOutputStream out = new DataOutputStream(urlOutputStream());
//将上传扥内容写入到流中
out.writeBytes(content); out.flush(); out.close();
//设置上传的参数 使用等号方式 左边键 右边值
String content = "str="+URLEncoder.encode("hello world !","gb2312");
//获取数据
BufferReader buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine = null;
//循环获取得到数据
while((inputLine = buffer.readLine())!=null){
//
result += inputLine+"\n";
}
//关闭输入流
reader.close();
//关闭连接
urlConn.close();
//处理数据..................
}catche(IOException e){Log.e(DEBUG_TAG,"IOException")}
}