Android HTTP通信

第一步:

在配置的XML文件中加入获取权限的代码:

1
2
<uses-permissionandroid:name="android.permission.INTERNET"/>
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>

第二步:

创建URL 对象 url
创建 HttpURLConnection 对象 httpURLConnection

1
2
HttpURLConnection httpURLConnection = null;
httpURLConnection=(HttpURLConnection)url.openConnection();(判断是否为空)

再设置3个参数:

1
2
3
httpURLConnection.setRequestMethod("GET");//请求方式
httpURLConnection.setReadTimeout(10000);//读取时间上限
httpURLConnection.setConnectTimeout(15000);//连接时间上限

1
2
3
4
5
6
7
进行连接:httpURLConnection.connect();
创建InputStream对象 inputStream
inputStream=httpURLConnection.getInputStream()
得到输入流之后 要对输入流解析
编写个解析输入流方法后调用
String result=readStringByInputStream(inputStream);
将得到的 result 返回

第三步:

编写 readStringByInputStream方法

首先判断下参数是否为空

创建StringBuilder 对象 output=new StringBuilder();

创建InputStreamReader 类 inputStreamReader

1
inputStreamReader=newInputStreamReader(inputStream,Charset.forName("UTF-8"));

创建 BufferedReader 类 reader =newBufferedReader(inputStreamReader);

循环读取:

1
2
3
4
5
Stringline=reader.readLine();
while(line!=null){
output.append(line);
line=reader.readLine();
}

最后返回 return output.toString();

总结:将这2个功能封,传入个URL 即可读取出web数据,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class HttpContentGet{
static public String getHttpCentent(URL url){
if (url==null){
return null;
}
HttpURLConnection httpURLConnection = null;
try{

httpURLConnection = (HttpURLConnection) url.openConnection();
if (httpURLConnection==null){
return null;
}
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
String result = readStringByInputStream(inputStream);
return result;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
static public String readStringByInputStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream!=null){
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while(line != null){
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}