2.HttpClient接口
代码:
/设置/url
String httpUrl = "http://10.0.2.2/****" ;
//HttpGet对象获取
HttpGet httpRequest = new HttpGet(httpUrl);
try{
//HttpClient对象获取
HttpClient httpClient = enw DefaultHttpClient();
//请求httpClient,取得response
HttpResponse httpResponse = httpClient.execute(httpRequest);
//请求成功
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//获取数据
String result = EntityUtils.toString(httpResponse.getEntity());
}
}catch(Exception e){} //ClientProtocol IOException
POST:需要使用NameValuePair来保存数据,BaseNameValuePair构造被传递数据参数,add方法添加到NameValuePair
/设置/url
String httpUrl = "http://10.0.2.2/****" ;
//HttpGet对象获取
HttpPost httpRequest = new HttpPost(httpUrl);
//使用 NameValuePair保存需要传递的数据
List<NameValuePair> parmas = new ArrayList<NameValuePair>();
//添加需要传递的数据
params.add(new BaseNameValuePair("str","hello world"));
try{
//设置字符集
HttpEntity httpEntity = new UrlEncodedFormEntity(params,"fb2312");
//请求默认的HttpRequest
httpRequest.setEntity(httpEntity);
//HttpClient对象获取
HttpClient httpClient = enw DefaultHttpClient();
//请求httpClient,取得response
HttpResponse httpResponse = httpClient.execute(httpRequest);
//请求成功
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//获取数据
String result = EntityUtils.toString(httpResponse.getEntity());
}
}catch(Exception e){} //ClientProtocol IOException