您的位置:首页 > 理论基础 > 计算机网络

Http 模拟form表单提交Post请求

2017-04-13 14:59 381 查看
private static Logger log = LoggerFactory.getLogger(HttpPostUtil.class);

public static  String reqXinyi(String urls, String appkey,String data,String sign) throws IOException{
ObjectMapper mapper = new ObjectMapper();
String param= null;
String b = null;
try {
param = "appKey="+ URLEncoder.encode(appkey, "UTF-8")+"&data="+URLEncoder.encode(data, "UTF-8")+"&sign="+URLEncoder.encode(sign, "UTF-8");
log.info("拼接请求参数param:"+param);
} catch (UnsupportedEncodingException e) {
log.error("拼接请求参数错误");
e.printStackTrace();
}
log.info("开始发送请求");
URL url = new URL(urls);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
// 设置请求方法为POST
httpConn.setRequestMethod("POST");
// 设置是否需要输出
httpConn.setDoOutput(true);
// 设置是否需要允许输入
httpConn.setDoInput(true);
// 设置请求属性
httpConn.setRequestProperty("Content-Length",String.valueOf(param.getBytes().length));
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// 向服务器端写数据
OutputStream out = httpConn.getOutputStream();
out.write(param.getBytes("UTF-8"));
out.close();
// 接收服务器返回的数据
InputStream in = httpConn.getInputStream();
ByteArrayOutputStream resp = new ByteArrayOutputStream();
byte[] tempbytes = new byte[100];
int byteread = 0;
while ((byteread = in.read(tempbytes)) != -1) {
resp.write(tempbytes, 0, byteread);
}
b = new String(resp.toByteArray());
log.info("调用接口返回:{}",b);
return b;
}


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