android 服務器操作類
來源:程序員人生 發布時間:2014-12-12 08:34:29 閱讀次數:2931次
簡單 方便
/**
* @author think
*以同步方式發送Http要求
*/
public class ApacheHttpClient {
/**
* @return
*
*/
public String httpGet(String uri) {
String response=null;//響應
HttpClient httpClient=new DefaultHttpClient();
//創建HttpGet對象
HttpGet httpGet=new HttpGet(uri);
HttpResponse httpResponse;
try {
//使用execute方法發送HTTP GET要求,并返回HttpResponse對象
httpResponse=httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();//返回碼 ,
if (statusCode==HttpStatus.SC_OK) {
//取得返回結果
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方式發送要求
* @param url 要求地址
* @param params 參數 ,Post方式必須用NameValuePair[]陣列貯存參數
* @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 {
//設置httpPost要求參數
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//使用execute方法發送HTTP Post要求,并返回HttpResponse對象
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;
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈