您的位置:首页 > 理论基础 > 计算机网络

android 之http网络请求之基本的GET,POST请求一

2013-05-16 18:01 681 查看
首先封装一个方法获取httpclient对象

public static HttpClient getHttpClient() {

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

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; }

//post----------------------------------------------------------------------------------------

post请求在数据方法封装:

public static String doPostUrl(String url, List<NameValuePair> params) { getHttpClient(); /* 建立HTTPPost对象 */ HttpPost httpRequest = new HttpPost(url);

String strResult = "doPostError";

try { /* 添加请求参数到请求对象 */ httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); /* 发送请求并等待响应 */ HttpResponse httpResponse = httpClient.execute(httpRequest); /* 若状态码为200 ok */ if (httpResponse.getStatusLine().getStatusCode() == 200) { /* 读返回数据 */ strResult = EntityUtils.toString(httpResponse.getEntity());

Log.e("doPostUrl---------->", strResult); } else { strResult = "Error Response: " + httpResponse.getStatusLine().toString(); } } catch (ClientProtocolException e) { strResult = e.getMessage().toString(); e.printStackTrace(); } catch (IOException e) { strResult = e.getMessage().toString(); e.printStackTrace(); } catch (Exception e) { strResult = e.getMessage().toString(); e.printStackTrace(); }

return strResult; }

前面类里调用的代码:

List<NameValuePair> postDate = new ArrayList<NameValuePair>();
postDate.add(new BasicNameValuePair("ak",
"B992b6c4de2f497aad02ea7fe60314ce"));
postDate.add(new BasicNameValuePair("query", URLEncoder.encode("网吧")));
postDate.add(new BasicNameValuePair("output", "json"));
postDate.add(new BasicNameValuePair("page_size", "100"));
postDate.add(new BasicNameValuePair("location", "39.915,116.404"));

//get----------------------------------------------------------------------------------------

public static String doGetUrl(String url, Map<?, ?> params) { getHttpClient(); /* 建立HTTPGet对象 */ String paramStr = ""; Iterator<?> iter = params.entrySet().iterator(); while (iter.hasNext()) { @SuppressWarnings("rawtypes") 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; } HttpGet httpRequest = new HttpGet(url);

String strResult = "doGetError";

try {

/* 发送请求并等待响应 */ HttpResponse httpResponse = httpClient.execute(httpRequest); /* 若状态码为200 ok */ if (httpResponse.getStatusLine().getStatusCode() == 200) { /* 读返回数据 */ strResult = EntityUtils.toString(httpResponse.getEntity());

Log.e("doGet--------->", strResult); } else { strResult = "Error Response: " + httpResponse.getStatusLine().toString();

Log.e("doPostUrl---------->", strResult); } } catch (ClientProtocolException e) { strResult = e.getMessage().toString(); e.printStackTrace(); } catch (IOException e) { strResult = e.getMessage().toString(); e.printStackTrace(); } catch (Exception e) { strResult = e.getMessage().toString(); e.printStackTrace(); }

Log.v("strResult", strResult);

return strResult; }

前面类里调用的方法:

HashMap<String, String> hash = new HashMap<String, String>();
hash.put("ak", "6cb3f458a482fcd009414370808ea219");
hash.put("query", URLEncoder.encode("网吧"));//进行URLEncoder对汉字进行编码
hash.put("output", "json");

//另外的psst---------------------------------------------------------------

public static String doPost(List<NameValuePair> params, String url) throws Exception { String result = null; // 新建HttpPost对象 HttpPost httpPost = new HttpPost(url); // 设置字符集 HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // 设置参数实体 httpPost.setEntity(entity); // 获取HttpClient对象 HttpClient httpClient = new DefaultHttpClient(); HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

// 连接超时 httpClient.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); // 请求超时 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);

// addcookie // Cookie cookie = new BasicClientCookie("", ""); // CookieSpecBase cookieSpecBase = new BrowserCompatSpec(); // List<Cookie> cookies = new ArrayList<Cookie>(); // cookies.add(cookie); // cookieSpecBase.formatCookies(cookies); // httpPost.setHeader(cookieSpecBase.formatCookies(cookies).get(0));

try { // 获取HttpResponse实例 HttpResponse httpResp = httpClient.execute(httpPost); /** * get cookie List<Cookie> * cookiess=client.getCookieStore().getCookies(); * cookiess.get(0).getName(); cookiess.get(0).getValue(); */

// 判断是够请求成功 if (httpResp.getStatusLine().getStatusCode() == 200) { // 获取返回的数据 result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");

Log.e("返回数据-------------->", result); } else { Log.i("HttpPost", "HttpPost方式请求失败"); } } catch (ConnectTimeoutException e) { result = TIME_OUT; }

return result; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: