HttpClient接口
在Android6.0中,HttpClient库已经被移除
Android SDK附带的Apache的HttpClient,使用步骤如下:
- 使用DefaultHttpClient类实例化HttpClient对象;
- 创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象;
- 调用execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象;
- 通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。
HttpGet示例代码如下:
public void sendGetRequest(String Url) throws Exception {
//创建HttpClient对象,设置默认参数
HttpClient mHttpClient = new DefaultHttpClient();
//创建HttpGet对象
HttpGet mHttpGet = new HttpGet(Url);
//添加Header
mHttpGet.addHeader("Connection", "Keep-Alive");
//执行Http请求
HttpResponse mResponse = new mHttpClient.execute(mHttpGet );
HttpEntity mHttpEntity = new mResponse().getEntity();
if (mHttpEntity != null) {
InputStream mInputStream = mHttpEntity.getContent();
BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream));
StringBuilder mStringBuilder = new StringBuilder();
String line = null;
try{
while((line = mBufferedReader.readLine()) != null ) {
mStringBuilder.append(line );
}
} catch (IOException e) {
e.printStackTrace();
} finally {
mInputStream.close();
}
Log.e("","###请求结果:" + mStringBuilder.toString());
}
}
HttpPost示例代码如下:
public void sendPostRequest(String Url) throws Exception {
//创建HttpClient对象,设置默认参数
HttpClient mHttpClient = new DefaultHttpClient();
//创建HttpGet对象
HttpGet mHttpPost = new HttpPost(Url);
//添加Header
mHttpGet.addHeader("Connection", "Keep-Alive");
//使用NameValuePair>来保存要传递的Post参数
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//添加要传递的参数,BasicNameValuePair是存储键值对的类
postParameters.add(new BasicNameValuePair("username", "myname"));
postParameters.add(new BasicNameValuePair("password", "mypwd"));
//实例化UrlEndecodedFormEntity对象
UrlEncodedFormEntity mUrlEncodedFormEntity = new UrlEncodedFormEntity(postParameters);
//使用HttpPost对象来设置UrlEncodedFormEntity的Entity
mHttpPost.setEntity(mUrlEncodedFormEntity );
//执行Http请求
HttpResponse mResponse = new mHttpClient.execute(mHttpPost );
HttpEntity mHttpEntity = new mResponse().getEntity();
if (mHttpEntity != null) {
InputStream mInputStream = mHttpEntity.getContent();
BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream));
StringBuilder mStringBuilder = new StringBuilder();
String line = null;
try{
while((line = mBufferedReader.readLine()) != null ) {
mStringBuilder.append(line );
}
} catch (IOException e) {
e.printStackTrace();
} finally {
mInputStream.close();
}
Log.e("","###请求结果:" + mStringBuilder.toString());
}
}
HttpURLConnection接口---Google官方推荐
HttpURLConnection的压缩和缓存机制可以有效地减少网络访问的流量,提升速度和省电。
HttpURLConnection默认使用Get请求:
public void sendRequest(String url) throws IOException {
String line = null;.
String result = null;
//使用HttpURLConnection 打开链接
try{
Url mUrl = new Url(url);
HttpURLConnection mHttpURLConnection = (HttpURLConnection ) mUrl.openConnection();
//读取响应的内容(流)
InputStreamReader mInputStreamReader = new InputStreamReader(new InputStream(mHttpURLConnection.getInputStream()));
BufferedReader mBufferedReader = new BufferedReader(mInputStreamReader );
if ((line = mBufferedReader.readLine())) {
result = line + “\n”;
}
Log.e("", "请求结果:" + result);
} catch ((MalformedURLException e)
{
Log.e(DEBUG_TAG, "MalformedURLException");
} finally {
mInputStreamReader.close();
mHttpURLConnection.disconnect();
}
}
HttpURLConnection的Post请求
public void sendRequest(String url) throws IOException {
String line = null;.
String result = null;
try{
Url mUrl = new Url(url);
HttpURLConnection mHttpURLConnection = (HttpURLConnection ) mUrl.openConnection();
//设置读取超时为10秒
mHttpURLConnection.setReadTimeout(10000);
//设置链接超时为15秒
mHttpURLConnection.setConnectionTimeout(15000);
//设置请求方式
mHttpURLConnection.setRequestMethod("Post");
//接收输入流
mHttpURLConnection.setDoInput(true);
//启动输出流,当需要传递参数时需要开启
mHttpURLConnection.setDoOutput(true);
//添加Header
mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
//添加请求参数
List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
paramsList .add(new BasicNameValuePair("username", "myname"));
paramsList .add(new BasicNameValuePair("password", "mypwd"));
//将参数写入到输出流
wriParams(mHttpURLConnection.getOutputStream(), paramsList);
//发起请求
mHttpURLConnection.connect();
BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mHttpURLConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
while((line = mBufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch ((MalformedURLException e)
{
Log.e(DEBUG_TAG, "MalformedURLException");
} finally {
mHttpURLConnection.disconnect();
}
}
private void writeParams(OutputStream mOutputStream, List<NameValuePair> paramsList){
StringBuilder paramStr = new StringBuilder();
for (NameValuePair pair : paramsList) {
if (!TextUtils.isEmpty(paramStr)) {
paramStr.append("&"):
}
paramStr.append(URLEncoder.encode(pair.getName(), "UTF-8"));
paramStr.append("=");
paramStr.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mOutputStream, "UTF-8"));
//将参数写入输出流
writer.write(paramStr.toString());
writer.flush();
writer.close();
}
注:任何输出流都是有缓冲区的,Bufferedxxx这种输出流提供可配置缓冲区大小,其他输出流都是有默认大小的缓冲区的,FileWriter的flush()方法是从OutputStreamWriter中继承来的,其作用就是 清空缓冲区并完成文件写入操作的。