form表单提交
1.form表单get请求提交数据
<div class="margin-bottom"> <label class="label">平台商户号</label> <input type="text" class="input" placeholder="平台商户号" name="platformNo" value="S0000000101"/> </div> <div class="margin-bottom"> <label class="label">应用号</label> <input type="text" class="input" placeholder="应用号" name="appNo" value="ed490ab98275d440ebc20dd75464ca2c"/> </div> <div class="margin-bottom"> <label class="label">银行卡号</label> <input type="text" class="input" placeholder="银行编码" name="bankNo" value="6216261000000000018"/> </div> <div class="margin-bottom"> <label class="label">商户订单号</label> <input type="text" class="input" placeholder="商户订单号" id="orderNo" name="orderNo" value="893275279472947927jfjf"/> </div> <div class="margin-bottom"> <label class="label">支付类型</label> <select name="payType" class="input"> <option value="h5_quick">网银快捷支付</option> </select> </div> <div class="margin-bottom"> <input type="submit" value="from提交"/> </div> </form> <hr class="bg-blue"/> <div id="error" class="margin" style="display:none"> <p class="text-red bg-red-light padding"></p> </div> <div id="success" class="margin" style="display:none"> <div id="qrcode"></div> </div> </div>
2.后台方法(get 如果传递的值有数组,目前无法访问到方法)
@ResponseBody @RequestMapping(value = "/netQuick") protected void netQuick(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, String> data = new HashMap<String, String>(); Enumeration<String> names = request.getParameterNames(); String params = "?"; while (names.hasMoreElements()) { String name = names.nextElement(); String value = request.getParameter(name); data.put(name, value); params += name + "=" + value + "&"; } ReqPayNetVo reqPayVo = JSON.parseObject(JSON.toJSONString(data), ReqPayNetVo.class); String env = request.getParameter("env"); String host = env; System.err.println("host:" + host); if (env.equalsIgnoreCase("test")) { host = Config.dev_url; } else if (env.equalsIgnoreCase("local")) { host = Config.local_url; } else { host = Config.pro_url; } String reqData = ApiSignUtils.toSignStrMap(JSON.parseObject(JSON.toJSONString(reqPayVo)), null, true); String path = host + "/pay/quick?" + reqData; response.sendRedirect(path); }
后台方法(post请求)
HttpClient模拟表单提交数据(File(文件)类型和普通类型)
传递过去的值实际就是map,最标准的格式就是form表单界面直接提交数据
普通方法:
private static String post(String url, int connectTimeout, int readTimeout,
Map<String, String> data, String encoding) throws IOException {
HttpPost post = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout)
.setExpectContinueEnabled(false).build();
post.setConfig(requestConfig);
if (null != data && !data.isEmpty()) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String key : data.keySet()) { formparams.add(new BasicNameValuePair(key, data.get(key) .toString())); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( formparams, encoding); post.setEntity(formEntity); } CloseableHttpResponse response = null; if (url.startsWith("https")) {// https response = createSSLClient().execute(post); } else { response = httpclient.execute(post); } HttpEntity entity = response.getEntity(); try { if (entity != null) { String str = EntityUtils.toString(entity, encoding); return str; } } finally { /* if (entity != null) { entity.getContent().close(); }*/ if (response != null) { response.close(); } } return null; }
HttpClient模拟表单提交数据(File(文件)类型)
public void uploadFormFile() {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
int timeOut = 30000;
// 设置本地fiddler代理,方便排查问题
//因为是基于tomcat进行的请求转发,所以在代码中手动添加代理
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut)
.setConnectTimeout(timeOut).setSocketTimeout(timeOut).setProxy(proxy).build();
//设置请求地址
HttpPost httpPost = new HttpPost("XXXX");
httpPost.setConfig(requestConfig);
/* * 这里是一个很容易被疏忽的地方 * 关于表单提交,会有两种content-Type: * 1、application/x-www-form-urlencoded:不能进行文件的上传,我们一般form表单默认就是这个类型 * 2、multipart/form-data ,用于文件的上传,设置表单的MIME编码,二进制传输数据,参数会以boundary进行分割 * 很多人选择文件上传的话,就会直接设置这个地方为multipart/form-data, * 但是这里面有个boundary参数属性,假如我们手动设置为multipart/form-data,则会导致boundary无法生成。所以这里千万不要设置 */ //httpPost.setHeader("content-Type", "multipart/form-data"); //构建参数 MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); /* * RFC6532=utf-8,STRICT=iso-8859-1 * 这里如果存在中文乱码,一定要用RFC6532 * 如果没有中文,这行可以不要 */ multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532); /* * 这个设置并无卵用,害我纠结了半天是不是编码方式设置错了 */ //multipartEntityBuilder.setCharset(Charset.forName("UTF-8")); /* * 这个地方是个深渊巨坑!!!! * 这里千万不要设置ContentType = multipart/form-data, 不然 boundary 这个参数就不会自动生成 */ //org.apache.http.entity.ContentType.create("multipart/form-data",Charset.forName("UTF-8")); /* * 这里也是个深渊巨坑!!!! * 这里是设置需要传输的文件 * 第一个参数是key值,也就是对面拿什么来接收 * 第二个参数是文件 file * 第三个参数 一种类型,具体也也不太清楚 * 第四个参数 这个就是巨坑了!!看源码,当不填这个值的时候,会取file.getName; * 但是一定要记住,如果文件是远程地址的,这样再通过http传的时候会出现错误,所以需要取到最原始的文件后缀名!!!最好就是用字节流去读取这个文件 * * 这里的第三个参数和第四个参数必须要设置,不然后续服务读取不到这个文件流 */ File file = new File("http://aaa/bbb/cc/ddd.jpg"); multipartEntityBuilder.addBinaryBody("image", file, ContentType.DEFAULT_BINARY, file.getName()); //这里是设置string类型的传输数据 /* * 这里是设置字符编码 * 这个地方也是坑,但是网上很多文章都会设置,所以很少人出问题 * 根据我的理解,就是整体传输,需要给表单设置一个编码,然后文件传输,也需要设置编码,文字传输,也需要设置编码 * 很多小伙伴都会因为某个地方没有设置编码,导致传输失败。这个地方可能理解有误,欢迎大家来指导。 */ org.apache.http.entity.ContentType contentType = org.apache.http.entity.ContentType.create("text/plain",Charset.forName("UTF-8")); multipartEntityBuilder.addPart("name", new StringBody("zhangsan", contentType)); multipartEntityBuilder.addPart("age", new StringBody("18", contentType)); httpPost.setEntity(multipartEntityBuilder.build()); try { org.apache.http.HttpResponse response = httpClient.execute(httpPost); /* * int statusCode= response.getStatusLine().getStatusCode(); * 这里是返回状态码,真正在项目中,需要判断返回码是否为200,看是否发送成功 * 这里就不展开写了 */ System.out.println( EntityUtils.toString(response.getEntity(), "UTF-8")); } catch (Exception e) { }finally { try { httpClient.close(); } catch (IOException e) { } } }
}
3.接收方法:
public ResultVo<respaynetquickvo> prePayQuick(ReqPayNetQuickVo vo, HttpServletRequest request) {
ResultVo<respaynetquickvo> resultVo = new ResultVo<>();
String ip = WebUtil.getIpAddr(request);
logger.info("cmd=PayNetServiceImpl:prePay msg=请求原始字符串:" + JSON.toJSONString(vo) + ", ip=" + ip);
if (vo == null) {
resultVo.setCode(ResCode.COMMON_ERROR);
resultVo.setMsg("请求数据不能为空");
logger.info("cmd=PayNetServiceImpl:prePay msg=请求参数为空, 请求ip=" + ip);
return resultVo;
}</respaynetquickvo></respaynetquickvo>
}
纯用form表单提交:(完全用form表单提交,不经过中间后台的转换,get/post请求都可以把json多参数的值传递过去,但是如果用后台代码访问,get请求就访问不过去,post才可以)
type="text" class="input" placeholder="秘钥" name="secret" value="393c7f6922f51ea5ebd4c98246fa11dd"/> </div> <div class="margin-bottom"> <label class="label">货币代码</label> <input type="text" class="input" placeholder="货币代码" name="currency" value="cny"/> </div> <div class="margin-bottom"> <label class="label">商品名称</label> <input type="text" class="input" placeholder="商品名称" name="goodsTitle" value="电脑" /> </div> <div class="margin-bottom"> <label class="label">商户号</label> <input type="text" class="input" placeholder="商户号" name="merchantNo" value="S0000000103"/> </div> <div class="margin-bottom"> <label class="label">分账明细</label> <input type="text" id="shareDetail" class="input" placeholder="分账明细" name="shareDetail" value='[{"shareAmount":50,"merchantNo":"M0001"},{"shareAmount":50,"merchantNo":"M0002"}]'/> </div> <div class="margin-bottom"> <input type="submit" value="form提交"/> </div> </form> <hr class="bg-blue"/> <div id="error" class="margin" style="display:none"> <p class="text-red bg-red-light padding"></p> </div> <div id="success" class="margin" style="display:none"> <div id="qrcode"></div> </div> </div></form>