您的位置:首页 > 运维架构 > Apache

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: