Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。
下面要说的是HttpURLConnection ,HttpURLConnection 有两种方式:
get和post
//HttpURLConnection get
try
{
URL url =
new
URL(
"http://www.51cto.com/index.jsp?par=123456"
);
//使用HttpURLConnection打开连接
HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
//去服务器求请
urlConn.setConnectTimeout(5*1000);
//设置输入和输出流
urlConn.setDoOutput(
true
);
urlConn.setDoInput(
true
);
//得到读取的内容(流)
InputStreamReader in =
new
InputStreamReader(urlConn.getInputStream());
//获取服务器返回的东西
// 为输出创建BufferedReader
BufferedReader buffer =
new
BufferedReader(in);
String inputLine =
null
;
//使用循环来读取获得的数据
while
(((inputLine = buffer.readLine()) !=
null
))
{
//我们在每一行后面加上一个"\n"来换行
resultData
+= inputLine +
"\n"
;
}
//关闭InputStreamReader
in.close();
//关闭http连接
urlConn.disconnect();
}
catch
(Exception e) {
//
TODO
: handle exception
}
//HttpURLConnection post
try
{
URL url =
new
URL(
"http://www.51cto.com/index.jsp?par=123456"
);
//使用HttpURLConnection打开连接
HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
//去服务器求请
urlConn.setConnectTimeout(5*1000);
//设置输入和输出流
urlConn.setDoOutput(
true
);
urlConn.setDoInput(
true
);
urlConn.setRequestMethod(
"POST"
);
urlConn.setRequestProperty(
"Content-Type"
,
"application/x-www-form-urlencoded"
);
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
urlConn.connect();
DataOutputStream out =
new
DataOutputStream(urlConn.getOutputStream());
//要上传的参数
String content =
"par="
+ URLEncoder.encode(
"ABCDEFG"
,
"gb2312"
);
//将要上传的内容写入流中
out.writeBytes(content);
//刷新、关闭
out.flush();
out.close();
//得到读取的内容(流)
InputStreamReader in =
new
InputStreamReader(urlConn.getInputStream());
//获取服务器返回的东西
// 为输出创建BufferedReader
BufferedReader buffer =
new
BufferedReader(in);
String inputLine =
null
;
//使用循环来读取获得的数据
while
(((inputLine = buffer.readLine()) !=
null
))
{
//我们在每一行后面加上一个"\n"来换行
resultData
+= inputLine +
"\n"
;
}
//关闭InputStreamReader
in.close();
//关闭http连接
urlConn.disconnect();
}
catch
(Exception e) {
//
TODO
: handle exception
}