post模拟表单数据提交--利用apache的jar包
2015-08-14 14:40
756 查看
<span style="font-size:18px;">import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; //提交客户端表单数据 public class HttpUtil { //path为服务器地址,map为表单参数,encode为表单数据指定码表编码,得到服务器返回过来的数据按encode解码 public static String sendByPost(String path,HashMap<String,String> map,String encode) throws ClientProtocolException, IOException { //先把要提交的每对儿数据封装成NameValuePair类型的 List<NameValuePair> list = new ArrayList<NameValuePair>(); for(Map.Entry<String, String> en:map.entrySet()) { list.add(new BasicNameValuePair(en.getKey(), en.getValue())); } //把要提交的数据组织成提交的格式 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,encode); //创建提交方式对象 HttpPost post= new HttpPost(path); post.setEntity(entity); //创建执行提交的对象 HttpClient client = new DefaultHttpClient(); //执行提交 HttpResponse response = client.execute(post); InputStream in=null; if(response.getStatusLine().getStatusCode()==200) { in = response.getEntity().getContent(); return getResult(in, encode); } return null; } public static String getResult(InputStream in,String encode) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len=0; while((len = in.read(b))!=-1) { baos.write(b,0,len); } return new String(baos.toByteArray(),encode); } } </span>
相关文章推荐
- 利用apache来做集群,实现负载均衡
- [转载] Apache Lucene初探
- Apache端口复用-模块rootme
- Apache的压力测试工具ab
- Python开发入门与实战16-APACHE部署
- 如何编译Apache Hadoop2.6.0源代码
- apache activemq 学习笔记
- org.apache.commons.lang3功能示例
- 优化Apache,提高并发
- Apache2 Axis2/C 搭建 hello world
- Apache配置文件详解
- Amazon Linux 编译安装 Apache 2.4 + PHP 5.5
- org.apache.hadoop.hdfs.server.datanode.DataNode: Exception in BPOfferService for Block pool
- 服务器配置apache2.4+php5.6+mysql
- Spark Shuffle过程的一些小结(译 Shuffle Performance in Apache Spark)
- Linux+Apache+DB2+PHP环境配置
- django apache 发布
- No plugin found for prefix 'jetty' in the current project and in the plugin groups [org.apache.mave
- Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of
- linux下安装apache服务器