模拟发送Http请求我们可以使用HttpURLConnection类进行操作,但是Android平台集成了功能强大且编写更容易的commons-httpclient.jar,因此在这里介绍如何通过commons-httpclient进行Http请求。发送Http请求可以有两种方式:一种是同步,一种是异步。由于我对异步不是很熟悉,所以这里先提供同步方式发送Http请求:
1、使用Get方式发送
public String httpGet(String url, String params) throws Exception
{
String response = null; //返回信息
if (null!=params&&!params.equals(""))
{
url += "?" + params;
}
// 构造HttpClient的实例
HttpClient httpClient = new HttpClient();
// 创建GET方法的实例
GetMethod httpGet = new GetMethod(url);
// 设置超时时间
httpGet.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(CONNECTION_TIMEOUT));
try
{
int statusCode = httpClient.executeMethod(httpGet);
if (statusCode == HttpStatus.SC_OK) //SC_OK = 200
{
InputStream inputStream = httpGet.getResponseBodyAsStream(); //获取输出流,流中包含服务器返回信息
response = getData(inputStream);//获取返回信息
}
else
{
LOG.debug("Get Method Statuscode : "+statusCode);
}
} catch (Exception e)
{
throw new Exception(e);
} finally
{
httpGet.releaseConnection();
httpClient = null;
}
return response;
}
2、使用Post方式发送
public String httpPost(String url, List<Parameter> params) throws Exception
{
String response = null;
HttpClient httpClient = new HttpClient();
PostMethod httpPost = new PostMethod(url);
//Post方式我们需要配置参数
httpPost.addParameter("Connection", "Keep-Alive");
httpPost.addParameter("Charset", "UTF-8");
httpPost.addParameter("Content-Type", "application/x-www-form-urlencoded");
httpPost.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(CONNECTION_TIMEOUT));
if (null!=params&¶ms.size()!=0)
{
//设置需要传递的参数,NameValuePair[]
httpPost.setRequestBody(buildNameValuePair(params));
}
try
{
int statusCode = httpClient.executeMethod(httpPost);
if (statusCode == HttpStatus.SC_OK)
{
InputStream inputStream = httpPost.getResponseBodyAsStream();
response = getData(inputStream);
}
else
{
LOG.debug("Post Method Statuscode : "+statusCode);
}
} catch (Exception e)
{
throw new Exception(e);
} finally
{
httpPost.releaseConnection();
httpClient = null;
}
return response;
}
3、构件NameValuePair
private NameValuePair[] buildNameValuePair(List<Parameter> params)
{
int size = params.size();
NameValuePair[] pair = new NameValuePair[size];
for(int i = 0 ;i<size;i++)
{
Parameter param = params.get(i);
pair[i] = new NameValuePair(param.getName(),param.getValue());
}
return pair;
}
4、获得返回数据
private String getData(InputStream inputStream) throws Exception
{
String data = "";
//内存缓冲区
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = -1;
byte[] buff = new byte[1024];
try
{
while((len=inputStream.read(buff))!=-1)
{
outputStream.write(buff, 0, len);
}
byte[] bytes = outputStream.toByteArray();
data = new String(bytes);
} catch (IOException e)
{
throw new Exception(e.getMessage(),e);
}
finally
{
outputStream.close();
}
return data;
}