首页
技术知识库
Task工作计划
网站简介
DON框架
后台管理
文章分类
JAVA
框架知识
操作系统
容器相关
数据库层
优化技术
界面编程
网络编程
开发工具
GO语言
其他
读书随笔
观影随笔
每日随笔
APP
httpclient代码模板
所属分类
:[JAVA] |
创建时间
:2014-05-17 |
文章属性
:原创 |
文章来源
:http://windfly.cn |
作者
:windfly
<pre class="java" name="code"> package cn.windfly.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; public class HttpClientUtil { private static Logger logger = Logger.getLogger(HttpClientUtil.class.getName()); public static String requestURLByGet(String url,Map<String, String> params) { HttpClient c = new DefaultHttpClient(); String result = null; String param = "?"; Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); param += "&"+entry.getKey()+"="+entry.getValue(); } url += param; try { HttpGet hget = new HttpGet(url); hget.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); hget.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); HttpResponse response = c.execute(hget); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } catch (Exception e) { logger.log(Level.SEVERE,e.getMessage(),e); }finally{ c.getConnectionManager().shutdown(); } return result; } public static String requestURLByPost(String url,Map<String, String> params) { HttpClient c = new DefaultHttpClient(); String result = null; List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } try { HttpPost hpost = new HttpPost(url); hpost.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); hpost.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); hpost.setEntity(new UrlEncodedFormEntity(list,"utf-8")); HttpResponse execute = c.execute(hpost); result = EntityUtils.toString(execute.getEntity()); } catch (Exception e) { logger.log(Level.SEVERE,e.getMessage(),e); }finally{ c.getConnectionManager().shutdown(); } return result; } } </pre>
返回