HttpClient经常在开发的过程中会用到 所以这个是必须掌握的啦
http请求主要常用的有get请求和post请求,如下:
//import 省略......public class HttpUtil { /** * HttpClient获取get请求的数据 * @param url 请求的地址 * @return 返回字符串 */ public static String getDataByGet(String url) { StringBuilder sb = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); // 设置网络超时参数 HttpConnectionParams.setConnectionTimeout(httpParams, 3000); HttpConnectionParams.setSoTimeout(httpParams, 5000); HttpGet request; try { // 发出request请求 request = new HttpGet(url); // 返回response响应 HttpResponse response = client.execute(request); // 判断请求是否成功 if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { //这边也可以作和post类似的操作 这个只是另一种情况 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"),8192); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } reader.close(); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } /** * HttpClient获取post请求<br/> * 例子:<br/> * List<NameValuePair > parms=new ArrayList<NameValuePair><br/> * parms.add(new BasicNameValuePair(“str”,"I am Post String”));<br/> * @param url 请求的地址 * @param parms 参数 * @return */ public static String getDataByPost(String url, List<NameValuePair> parms) { String out = null; HttpClient client = new DefaultHttpClient(); HttpPost request; try { // 发出request请求 request = new HttpPost(new URI(url)); request.setEntity(new UrlEncodedFormEntity(parms, HTTP.UTF_8)); // 返回response响应 HttpResponse response = client.execute(request); // 判断请求是否成功 if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { out = EntityUtils.toString(entity); } } } catch (Exception e) { e.printStackTrace(); } return out; }}