当前位置:   article > 正文

android开发 http,Android的网络开发Http协议详解之一

安卓开发http

public class HttpUtils {

private final static String TAG = HttpUtils.class.getSimpleName();

private BasicHttpParams httpParams;

private HttpClient httpClient;

/**

* 获取HttpClient对象(设置一些参数)

* @return

*/

public HttpClient getHttpClient() {

// 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的)

this.httpParams = new BasicHttpParams();

// 设置连接超时和 Socket 超时,以及 Socket 缓存大小

HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);

HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);

HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

// 设置重定向,缺省为 true

HttpClientParams.setRedirecting(httpParams, true);

// 设置 user agent

String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";

HttpProtocolParams.setUserAgent(httpParams, userAgent);

// 创建一个 HttpClient 实例

// 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient

// 中的用法,在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient

httpClient = new DefaultHttpClient(httpParams);

return httpClient;

}

//使用HTTP GET调用有一个缺点就是,请求的参数作为URL一部分来传递,

//以这种方式传递的时候,URL的长度应该在2048个字符之内。

//如果超出这个这范围,就要使用到HTTP POST调用。

/**

* @param params

*/

public static String HttpRequstDataByGet(String url, Map params) {

String paramStr = "";

Iterator iter = params.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry entry = (Map.Entry) iter.next();

Object key = entry.getKey();

Object val = entry.getValue();

paramStr += paramStr = "&" + key + "=" + val;

}

if (!paramStr.equals("")) {

paramStr = paramStr.replaceFirst("&", "?");

url += paramStr;

}

return HttpRequstDataByGet(url);

}

/**

* 利用get方式请求数据

* @param uri

*/

public static String HttpRequstDataByGet(String uri) {

String resultStr = null;

BufferedReader in = null;

try {

//得到HttpClient对象

HttpClient getClient = new DefaultHttpClient();

//得到HttpGet对象

HttpGet request = new HttpGet(uri);

//客户端使用GET方式执行请教,获得服务器端的回应response

HttpResponse response = getClient.execute(request);

//判断请求是否成功

if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){

Log.i(TAG, "请求服务器端成功");

//获得输入流

InputStream inStrem = response.getEntity().getContent();

in = new BufferedReader(new InputStreamReader(inStrem));

String lineStr;

StringBuffer string = new StringBuffer("");

while ((lineStr = in.readLine()) != null){

string.append(lineStr);

}

//关闭输入流

inStrem.close();

//另外一种方法strResult = EntityUtils.toString(httpResponse.getEntity());

}else {

Log.i(TAG, "请求服务器端失败");

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (in != null) {

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return resultStr;

}

public static String HttpRequstDataByPost(String url, Map params) {

List postParameters = new ArrayList();

Iterator iter = params.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry entry = (Map.Entry) iter.next();

Object key = entry.getKey();

Object val = entry.getValue();

//添加要传递的参数

postParameters.add(new BasicNameValuePair(key.toString(), val.toString()));

}

return HttpRequstDataByPost(url, postParameters);

}

/**

* @param url

* @return

*/

public static String HttpRequstDataByPost(String url, List params) {

String resultStr = null;

BufferedReader in = null;

try {

HttpClient client = new DefaultHttpClient();

HttpPost request = new HttpPost(url);

//实例化UrlEncodedFormEntity对象

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(

params);

//使用HttpPost对象来设置UrlEncodedFormEntity的Entity

request.setEntity(formEntity);

HttpResponse response = client.execute(request);

if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){

in = new BufferedReader(

new InputStreamReader(

response.getEntity().getContent()));

StringBuffer string = new StringBuffer("");

String lineStr = "";

while ((lineStr = in.readLine()) != null) {

string.append(lineStr + "\n");

}

in.close();

//另外一种方法resultStr = EntityUtils.toString(httpResponse.getEntity());

resultStr = string.toString();

System.out.println(resultStr);

}else {

Log.i(TAG, "请求服务器端失败");

}

} catch(Exception e) {

// Do something about exceptions

} finally {

if (in != null) {

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return resultStr;

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/210656
推荐阅读
相关标签
  

闽ICP备14008679号