Java模拟POST表单提交HttpClient操作
- public static void Login() {
- String url = "http://www.***.com/login";
- PostMethod postMethod = new PostMethod(url);
- // 填入各个表单域的值
- NameValuePair[] data = {
- new NameValuePair("account", "yijianfeng_vip@163.com"),
- new NameValuePair("nextUrl", ""),
- new NameValuePair("lcallback", ""),
- new NameValuePair("password ", "******"),
- new NameValuePair("persistent", "1"), };
- // 将表单的值放入postMethod中
- postMethod.setRequestBody(data);
- // 执行postMethod
- int statusCode = 0;
- try {
- statusCode = httpClient.executeMethod(postMethod);
- } catch (HttpException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
- // 301或者302
- if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
- || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
- // 从头中取出转向的地址
- Header locationHeader = postMethod.getResponseHeader("location");
- String location = null;
- if (locationHeader != null) {
- location = locationHeader.getValue();
- System.out.println("diandianLogin:" + location);
- } else {
- System.err.println("Location field value is null.");
- }
- return;
- } else {
- System.out.println(postMethod.getStatusLine());
- String str = "";
- try {
- str = postMethod.getResponseBodyAsString();
- } catch (IOException e) {
- e.printStackTrace();
- }
- System.out.println(str);
- }
- postMethod.releaseConnection();
- return;
- }
- 其中需要的jar包:
- 1、 commons-httpclient.jar
- 2、commons-codec.jar
- 3、commons-logging.jar
今天开发时,遇到利用Java中HttpClient类以POST方式提交数据,目标收到后中文乱码问题。
请求端代码:
- /**
- * HttpClient提交参数
- * @author sunyunfang@126.com
- */
- public static void main(String[] args) throws IOException {
- HttpClient client = new HttpClient();
- client.getHostConfiguration().setHost("127.0.0.1", 8081, "http");
- // 使用POST方式提交数据
- HttpMethod method = getPostMethod();
- client.executeMethod(method);
- // 打印服务器返回的状态
- System.out.println(method.getStatusLine());
- // 打印结果页面
- String response = new String(method.getResponseBodyAsString().getBytes("8859_1"));
- // 打印返回的信息
- System.out.println(response);
- method.releaseConnection();
- }
- // 使用POST方式提交数据
- private static HttpMethod getPostMethod() {
- String url = "/PushServer/notification.do?action=sendOneMsg";
- NameValuePair message = new NameValuePair("message", "消息内容。");
- post.setRequestBody(new NameValuePair[]{message});
- return post;
- }
- // 使用GET方式提交数据
- private static HttpMethod getGetMethod() {
- return new GetMethod("/PushServer/notification.do?action=sendOneMsg&message=abcd");
- }
目标端代码:
- /**
- * 供MsgServer远程调用
- * @param request
- * @param response
- * @return
- * @throws Exception
- * @author SunYunfang@126.com
- */
- public ModelAndView sendOneMsg(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- String message = ServletRequestUtils.getStringParameter(request, "message");
- }
这段代码执行后,目标能收到信息,但是中文乱码,也没有找到转码的方法。
经分析,原来使用 NameValuePair 加入的HTTP请求的参数最终都会转化为 RequestEntity
提交到HTTP服务器。接着在PostMethod的父类 EntityEnclosingMethod
中发现,只要重载getRequestCharSet()方法就能设置提交的编码(字符集)。
修正后:
- /**
- * HttpClient提交参数
- * @author SunYunfang@126.com
- */
- public static void main(String[] args) throws IOException {
- HttpClient client = new HttpClient();
- client.getHostConfiguration().setHost("127.0.0.1", 8081, "http");
- // 使用POST方式提交数据
- HttpMethod method = getPostMethod();
- client.executeMethod(method);
- // 打印服务器返回的状态
- System.out.println(method.getStatusLine());
- // 打印结果页面
- String response = new String(method.getResponseBodyAsString().getBytes("8859_1"));
- // 打印返回的信息
- System.out.println(response);
- method.releaseConnection();
- }
- // 使用POST方式提交数据
- private HttpMethod getPostMethod() {
- String url = "/PushServer/notification.do?action=sendOneMsg";
- PostMethod post = new UTF8PostMethod(url);
- NameValuePair message = new NameValuePair("message", "消息内容。");
- post.setRequestBody(new NameValuePair[]{message});
- return post;
- }
- //Inner class for UTF-8 support
- public static class UTF8PostMethod extends PostMethod{
- public UTF8PostMethod(String url){
- super(url);
- }
- @Override
- public String getRequestCharSet() {
- //return super.getRequestCharSet();
- return "UTF-8";
- }
- }
- // 使用GET方式提交数据
- private static HttpMethod getGetMethod() {
- return new GetMethod("/PushServer/notification.do?action=sendOneMsg&message=abcd");
- }
Java模拟POST表单提交HttpClient操作的更多相关文章
- java模拟from表单提交,上传图片
/** * java上传表单,有图片 * @param urlStr 上传地址 * @param textMap 表单参数 * @param fileMap 文件参数 key:文件名称 value:文 ...
- 通过HttpURLConnection模拟post表单提交
通过HttpURLConnection模拟post表单提交 package junit; import java.io.InputStream; import java.net.HttpURLConn ...
- js模拟form表单提交数据, js模拟a标签点击跳转,避开使用window.open引起来的浏览器阻止问题
js模拟form表单提交数据, js模拟a标签点击跳转,避开使用window.open引起来的浏览器阻止问题 js模拟form表单提交数据源码: /** * js模拟form表单提交 * @param ...
- js_ajax模拟form表单提交_多文件上传_支持单个删除
需求场景: 用一个input type="file"按钮上传多张图片,可多次上传,可单独删除,最后使用ajax模拟form表单提交功能提交到指定方法中: 问题:由于只有一个file ...
- Linux curl 模拟form表单提交信息和文件
Linux curl 模拟form表单提交信息和文件 curl是一个命令行方式下传输数据的开源传输工具,支持多种协议:FTP.HTTP.HTTPS.IMAP.POP3.TELNET等,功能超级强大 ...
- jquery模拟form表单提交并新打开页面
/** * form表单提交本页面打开 * @param url * @param params */ function postCurrent(url,params){ var form = $(& ...
- Ajax模拟Form表单提交,含多种数据上传
---恢复内容开始--- Ajax提交表单.使用FormData提交表单数据和上传的文件(这里的后台使用C#获取,你可以使用Java一样获取) 有时候前台的数据提交到后台,不想使用form表单上传,希 ...
- C#模拟POST表单提交 --- WebClient
string postString = "arg1=a&arg2=b";//这里即为传递的参数,可以用工具抓包分析,也可以自己分析,主要是form里面每一个name都要加进 ...
- 模拟post表单提交参数
Content-Type: application/x-www-form-urlencoded;charset=utf-8
随机推荐
- X窗口系统名词解释
前端时间Gentoo的桌面环境出了点问题,发现自己对Linux的桌面环境了解的很少,于是恶补了一下知识,以下名词解释基本上都是来自维基百科的条目和<Linux程序设计(第三版)>.一般而言 ...
- ZJOI2013 防守战线
题目 战线可以看作一个长度为\(n\)的序列,现在需要在这个序列上建塔来防守敌兵,在序列第\(i\)号位置上建一座塔有\(C_i\)的花费,且一个位置可以建任意多的塔,费用累加计算.有\(m\)个区间 ...
- 【linux】arm mm内存管理
欢迎转载,转载时请保留作者信息,谢谢. 邮箱:tangzhongp@163.com 博客园地址:http://www.cnblogs.com/embedded-tzp Csdn博客地址:http:// ...
- Python 基础编程
Python 打印九九乘法表: for i in range(1,10): for j in range(1,i+1): print j,'*',i,'=',j*i,' ', print '\n' P ...
- Ch06 验证
6.1 服务器端验证 6.1.1 Data Annotations验证 6.1.2 扩展ModelMetadtaProvider 6.2 客户端验证 6.2.1 客户端验证初步 6.2.2 ...
- perl 为什么要用引用来做对象呢?
perl 为什么要用引用来做对象呢? 因为一个重要的原因是 my 引用 脱离作用域,外部仍旧生效
- 基于visual Studio2013解决C语言竞赛题之1044数组处理
题目 解决代码及点评 /* 分别输入N和M个数到数组A和数组B中.把只在其中一个数组中出现的那些数送入到数组C中,并指出它们在A或B数组中的位置. */ #include <s ...
- hdu4431 Mahjong
Mahjong Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submi ...
- ctfmon.exe开机无法自己主动启动
打开命令提示符(開始菜单--执行--输入:cmd),输入下面命令(复制粘贴就可以): reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Ru ...
- tq2440+fedora安装qt4.5
1. make[1]: arm-none-linux-gnueabi-g++:命令未找到 make[1]: *** [.obj/release-shared-emb-arm/qatomic_arm.o ...