<pre name="code" class="java"><span style="font-size:18px;">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpConnection;
//模拟用户在网页提交表单
public class HttpUtils
{
//向服务器发送表单数据,接受返回的数据
public static String sendFormData(String path , HashMap<String,String> params,String code) throws IOException
{
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//得到要提交的数据
byte[] data = getFormData(params, code);
con.setRequestMethod("POST");
con.setConnectTimeout(3000);
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", data.length+"");
OutputStream out = con.getOutputStream();
out.write(data);
out.close();
InputStream in=null;
if(con.getResponseCode()==200)
{
in = con.getInputStream();
return getReturnData(in, code);
}
return null;
}
//把表单数据转换为用来传递的数据格式
public static byte[] getFormData(HashMap<String,String> params,String code) throws UnsupportedEncodingException
{
StringBuilder sb = new StringBuilder();
for(Map.Entry<String,String> en:params.entrySet())
{
sb.append(en.getKey())
.append("=")
.append(URLEncoder.encode(en.getValue(),code))
.append("&");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString().getBytes(code);
}
//得到 从服务器返回的数据按指定编码解码成的字符串
public static String getReturnData(InputStream in,String code) 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(),code);
}
}
</span>
post方式模拟表单向服务器提交数据
最新推荐文章于 2022-02-21 19:52:03 发布