Http Post请求的三种常见方式form表单 io流等 | 您所在的位置:网站首页 › form表单发送post请求 › Http Post请求的三种常见方式form表单 io流等 |
1 form 表单的提交形式 提交的时候只能其中的一种形式去提交 1 form表单的提交形式为构建键值对的形式: eg: List values = new ArrayList(); BasicNameValuePair base = new BasicNameValuePair("name","value"); values.add(base); values.add(new BasicNameValuePair("name","value1")); HttpEntity entity = new UrlEncodedFormEntity(values,"utf-8"); post.setEntity(entity);
2 io流的形式 主要是以字符串 字节数组 文件字符串、字节数组、输入流和文件: StringEntity,ByteArrayEntity,InputStreamEntity和FileEntity StringEntity sEnt = new StringEntity("aaaaa"); post.setEntity(sEnt); 3 form表单中含有文件的提交方式 MultipartEntity MultipartEntity entity = new MultipartEntity(); entity.addPart("name", new StringBody("value1", Charset.forName("UTF-8"))); entity.addPart("age", new StringBody("value2", Charset.forName("UTF-8"))); entity.addPart("file", new FileBody(new File("D:/test.txt"))); //需要上传的文件 post.setEntity(entity);
部分代码: @Test public void post(){ HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost("http://www.baiji.com.cn/goods-7138.html"); InputStream is; StringBuilder sb = new StringBuilder(); List values = new ArrayList(); BasicNameValuePair base = new BasicNameValuePair("name","value"); values.add(base); values.add(new BasicNameValuePair("name","value1")); try { HttpEntity entity = new UrlEncodedFormEntity(values,"utf-8"); //StringEntity sEnt = new StringEntity("aaaaa"); //要设置字符编码集,通过查看源码发现默认的是ios-8859-1,在提交的时候需要注意字符编码集 //public static final Charset DEF_CONTENT_CHARSET = Consts.ISO_8859_1; StringEntity sEnt = new StringEntity("aaaaa","utf-8"); post.setEntity(sEnt); //io流的形式 post.setEntity(entity); //form表单的形式 可以分别注释查看最后的请求结果 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { HttpResponse response = client.execute(post); byte[] b = new byte[10240]; int len =-1; is = response.getEntity().getContent(); while((len=is.read(b))!=-1){ sb.append(new String(b,0,len)); } System.out.println(sb.toString()); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } }
//如何查看请求不同形式可以通过抓包工具去查看 Wireshark 关于Wireshark的使用网上很多,授人以鱼不如授人以渔!
|
CopyRight 2018-2019 实验室设备网 版权所有 |