可以说目前市场上的android应用和游戏,客户端和服务端交互的主要方式是通过http请求实现的,因为方便,执行速度也快。本文主要介绍通过org.apache.http.client.HttpClient和java.net.HttpURLConnection实现http请求。包括Get和Post两种方式的调用方式。HttpClient需要和HttpGet、HttpPost、HttpEntity这几个类相互配合实现和服务端交互。HttpURLConnection则主要和InputStreamReader、 BufferedReader、DataOutputStream这几个类相互配合实现和服务端的交互。下面看完整的代码实现过程。
package com.figo.helloworld;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* @author zhuzhifei 客户端和服务端通过http进行交互,返回json格式字符串
*
*/
public class HttpActivity extends Activity {
private Button btnHttpClientGet;
private Button btnHttpClientPost;
private Button btnHttpUrlConGet;
private Button btnHttpUrlConPost;
private TextView tvContent;
private String tag = "HttpActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httptest);
btnHttpClientGet = (Button) findViewById(R.id.btnHttpClientGet);
btnHttpClientPost = (Button) findViewById(R.id.btnHttpClientPost);
btnHttpUrlConGet = (Button) findViewById(R.id.btnHttpUrlConGet);
btnHttpUrlConPost = (Button) findViewById(R.id.btnHttpUrlConPost);
tvContent = (TextView) findViewById(R.id.tvContent);
// HttpClient Get请求范例
btnHttpClientGet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
tvContent.setText("");
String httpUrl = "http://10.241.72.168:8083/figo/json/login.htm?userName=zhuzhifei&passWord=snda1234";
// HttpGet连接对象
HttpGet httpRequest = new HttpGet(httpUrl);
// 取得支持普通http请求的HttpClient对象
HttpClient httpclient = new DefaultHttpClient();
// 如果需要支持Https ssl加密的请求方式则使用以下这种HttpClient
// 请求HttpClient,取得HttpResponse
HttpResponse httpResponse;
try {
httpResponse = httpclient.execute(httpRequest);
// 请求成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字符串
String result = EntityUtils.toString(httpResponse
.getEntity());
tvContent.setText(result);
} else {
tvContent.setText("HttpGet请求出错");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tvContent.setText("HttpGet请求出错:" + e.getStackTrace());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tvContent.setText("HttpGet请求出错:" + e.getStackTrace());
}
}
});
// HttpClient Post请求范例
btnHttpClientPost.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
try {
tvContent.setText("");
// http地址
String httpUrl = "http://10.241.72.168:8083/figo/json/login.htm";
// HttpPost连接对象
HttpPost httpRequest = new HttpPost(httpUrl);
// 使用NameValuePair来保存要传递的Post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加要传递的参数
params.add(new BasicNameValuePair("userName", "zhuzhifei"));
params.add(new BasicNameValuePair("passWord", "snda1234"));
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params,
"gb2312");
// 请求httpRequest
httpRequest.setEntity(httpentity);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
// HttpStatus.SC_OK表示连接成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字符串
String result = EntityUtils.toString(httpResponse
.getEntity());
tvContent.setText(result);
} else {
tvContent.setText("请求错误!");
}
} catch (Exception e) {
// TODO: handle exception
}
}
});
// HttpURLConnection Get请求范例
btnHttpUrlConGet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// 使用HttpURLConnection打开连接
try {
tvContent.setText("");
URL url = new URL(
"http://10.241.72.168:8083/figo/json/login.htm?userName=zhuzhifei&passWord=snda1234");
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 得到读取的内容(流)
InputStreamReader in = new InputStreamReader(urlConn
.getInputStream());
// 为输出创建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
String result = "";
// 使用循环来读取获得的数据
while (((inputLine = buffer.readLine()) != null)) {
// 我们在每一行后面加上一个"\n"来换行
result += inputLine + "\n";
}
tvContent.setText(result);
// 关闭InputStreamReader
in.close();
// 关闭http连接
urlConn.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// HttpURLConnection Post请求范例
btnHttpUrlConPost.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
tvContent.setText("");
try {
// TODO Auto-generated method stub
String httpUrl = "http://10.241.72.168:8083/figo/json/login.htm";
// 获得的数据
String result = "";
URL url = new URL(httpUrl);
// 使用HttpURLConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 因为这个是post请求,设立需要设置为true
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
// 设置以POST方式
urlConn.setRequestMethod("POST");
// Post 请求不能使用缓存
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
urlConn.connect();
// DataOutputStream流
DataOutputStream out = new DataOutputStream(urlConn
.getOutputStream());
// 要上传的参数
String content = "userName=zhuzhifei&passWord=snda1234";
// 将要上传的内容写入流中
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"来换行
result += inputLine + "\n";
}
tvContent.setText(result);
} catch (Exception e) {
}
}
});
}
}
另外请参考两者之间的区别:HttpClient和HttpUrlConnection之间的区别