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
随机推荐
- Android Mediaplayer 调用release()的时候ANR
先stop,然后再release,最后吧media置为null
- docker学习笔记4:利用docker hub上的mysql镜像创建mysql容器
docker hub上有官方的mysql镜像,我们可以利用它来创建mysql容器,作为一个服务容器使用. 1.下载mysql镜像 docker pull mysql 2.创建镜像 docker run ...
- [HTML5游戏开发]简单的《找不同汉字版》,来考考你的眼力吧
本次 游戏 开发需要用到lufylegend.js开源游戏引擎,版本我用的是1.5.2(现在最新的版本是1.6.0). 引擎下载的位置: http://lufylegend.googlecode ...
- POJ 2112 Optimal Milking (二分+最短路径+网络流)
POJ 2112 Optimal Milking (二分+最短路径+网络流) Optimal Milking Time Limit: 2000MS Memory Limit: 30000K To ...
- 泛虚拟化技术(以Xen为例)
一.概述 最主要的特点是:修改Guest OS的内核代码.通过修改内核,使Guest OS明白自己是运行在R-1,不要直接去运行特权指令,如果要运行就去Hypercall(主动VMM陷入). ...
- MongoDB(二)——安装配置了解
前边介绍了MongoDB的大概理论知识,这篇来对MongoDB进行一下安装使用,支持安装在windows和linux上,当然了很多其它情况下我们是安装在linux上,由于毕竟server用linux的 ...
- spring mvc 与 jquery ajax
在 Spring mvc3中,响应.接受 JSON都十分方便. 使用注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON. 使用 @RequestBod ...
- hdu - 3572 - Task
题意:有N个作业,M台机器,每个作业1天只能同1台机器运行,每台机器1天只能运行1个作业,第i个作业需要pi天完成,且只能从Si到Ei中选Pi天,问能否完成所有作业(T <= 20, N< ...
- [Java聊天室server]实战之二 监听类
前言 学习不论什么一个稍有难度的技术,要对其有充分理性的分析,之后果断做出决定---->也就是人们常说的"多谋善断":本系列尽管涉及的是socket相关的知识,但学习之前,更 ...
- 用jQuery实现鼠标在table上移动进行样式变化
1.定义样式 <style type="text/css"> .striped { background-color:red; ...