无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。
1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。
如果使用HttpPost方法提交HTTP POST请求,则需要使用HttpPost类的setEntity方法设置请求参数。参数则必须用NameValuePair[]数组存储。
以发送连接请求时,需要设置链接超时和请求超时等参数,否则会长期停止或者崩溃。
- HttpParams httpParameters = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParameters, 10*1000);//设置请求超时10秒
- HttpConnectionParams.setSoTimeout(httpParameters, 10*1000); //设置等待数据超时10秒
- HttpConnectionParams.setSocketBufferSize(params, 8192);
- HttpClient httpclient = new DefaultHttpClient(httpParameters); //此时构造DefaultHttpClient时将参数传入
/** Http请求集成类
* HttpPost
*/
public class HttpServiceClient {
private static String serviceUrl;
/**
* Webservice 统一访问接口
* @param apiName 接口名称
* @param paramName 参数名称
* @param paramValue 参数数值
*/
public static String doAction(String apiName, List<String> paramName, List<String> paramValue){
String result = null;
try{
HttpClient client=new DefaultHttpClient();
// HttpGet httpRequst = new HttpGet(URI uri);
// HttpGet httpRequst = new HttpGet(String uri);
// 创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
HttpPost httpPostReq=new HttpPost(serviceUrl+apiName);
// httpPostReq.setHeader("Content-Type", "application/Json");
// JSONObject param = new JSONObject();
// POST 将需要传送的参数与值转化为相HttpPost能接受的类(key/value) Post不支持复杂数据类型,因为post没有定义传输数据结构的语义和规则
ArrayList<NameValuePair> paramList=new ArrayList<NameValuePair>();
for (int i = 0; i < paramName.size(); i++){
String name = paramName.get(i);
NameValuePair param = new BasicNameValuePair(name, paramValue.get(i));
paramList.add(param);
}
// StringEntity se = new StringEntity(param.toString());
// se.setContentEncoding(HTTP.UTF_8);
// 先将参数放入List,填入POST Entity中 ,再对参数进行URL编码
httpPostReq.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
// 使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。
HttpResponse resp = client.execute(httpPostReq);
if(resp.getStatusLine().getStatusCode()== HttpStatus.SC_OK){ //请求成功后执行
BufferedReader reader=new BufferedReader(
new InputStreamReader(resp.getEntity().getContent())
);
StringBuffer buff=new StringBuffer();
String inputLine;
while((inputLine=reader.readLine()) != null){
buff.append(inputLine);
} //result为调用接口后所返回的值
result = buff.toString();
Log.i(apiName, result); //获取响应对就的参数
}
}catch(Exception e){
Log.i("HttpServiceClient", e.toString());
}
return result;
}
public static void setServiceUrl(String serviceUrl) {
HttpServiceClient.serviceUrl = serviceUrl;
}
public static String getServiceUrl() {
return serviceUrl;
}
}