android 服務(wù)器操作類
來源:程序員人生 發(fā)布時(shí)間:2014-12-12 08:34:29 閱讀次數(shù):2939次
簡(jiǎn)單 方便
/**
* @author think
*以同步方式發(fā)送Http要求
*/
public class ApacheHttpClient {
/**
* @return
*
*/
public String httpGet(String uri) {
String response=null;//響應(yīng)
HttpClient httpClient=new DefaultHttpClient();
//創(chuàng)建HttpGet對(duì)象
HttpGet httpGet=new HttpGet(uri);
HttpResponse httpResponse;
try {
//使用execute方法發(fā)送HTTP GET要求,并返回HttpResponse對(duì)象
httpResponse=httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();//返回碼 ,
if (statusCode==HttpStatus.SC_OK) {
//取得返回結(jié)果
response=EntityUtils.toString(httpResponse.getEntity());
}
else {
response = "返回碼:"+statusCode;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();}
System.out.println(response);
return response;
}
/**
* 以Post方式發(fā)送要求
* @param url 要求地址
* @param params 參數(shù) ,Post方式必須用NameValuePair[]陣列貯存參數(shù)
* @return
* @throws Exception
*/
public String httpPost(String uri,List<NameValuePair> params) throws Exception{
String response=null;
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(uri);
try {
//設(shè)置httpPost要求參數(shù)
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//使用execute方法發(fā)送HTTP Post要求,并返回HttpResponse對(duì)象
HttpResponse httpResponse=httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();//返回碼 ,
if (statusCode==HttpStatus.SC_OK) {
response=EntityUtils.toString(httpResponse.getEntity());
System.out.println("______________"+response);
}
else {
response = "返回碼:"+statusCode;
System.out.println("______________"+response);
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)