android实现对网络的请求有两种方式:HttpURLConnection 或者 HttpClient;
1:通过HttpURLConnection来发起请求;
HttpURLConnection
1:创建实例:
URL url = new URL(“http://www.baidu.com“);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
2:设置请求方式:
get:从服务器请求数据;
post:向服务器提交数据;
connection.setRequestMethod(“GET”);
3:设置其他请求属性:
常用的有:
connection.setConnectTimeout(8000);//设置连接超时
connection.setReadTimeout(8000);//设置读取超时
4:获取输入流:
InputStream in = connection.getInputStream();
//如果是文本信息:
try{
InputStreamReader reader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(reader);
String allResult;
String line;
while((line = br.readLine()) != null){
allResult +=line;
}
}catch(IOException e){
e.printStackTrace();
}finally{
reader.close();
}
//其他信息:
try{
int num = 0;
byte[] res = new byte[];
while((num = in.read(res)) != -1){
}
}catch(IOException e){
e.printStackTrace();
}finally{
in.close
}
5:关闭连接:
connection.disConnect();
6:发送数据:
其余都一样:
OutPutstream out = connection.getOutPutStream();
//DataOutPutStream dataOut = new DataOutPutstream(out);
//dataOut.WriteBytes(String str);
out.write();
HttpClient已经被废弃!一下学习就当是长见识了!!!
通过HttpClient:
HttpClient只是一个接口,不能创建它的实例;一般创建的是DefaultHttpClient的实例;
HttpClient httpClient = new DefaultHttpClient();
1:发起GET请求:
HttpGet httpget = new HttpGet(“url”);
HttpClient.execute(httpget);
2:发起POST请求:
//创建post请求
HttpPost httppost = new HttpPost(“url”);
//创建NameValuePair的集合,并传入相关数据:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add("username","tom");
//创建UrlEncodedFormEntity实例
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf-8");
//使用httppost.setEntity()放入数据;
httppost.setEntity(entity);
//最后发送请求
HttpClient.execute(httppost);
3:执行这两个请求之后会返回一个HttpResponse对象,具体信息全部在这里
//首先取出响应码,判断请求是否成功:
//此处假设httpResponse是返回的响应
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 请求和响应都成功了
//通过getEntity()获取HttpEntity的实例
HttpEntity entity = httpResponse.getEntity();
//通过该EntityUtils.toString()方法将HttpEntity的信息提取出来
String response = EntityUtils.toString(entity,”utf-8”);
}