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
随机推荐
- Win7 和 MAC 系统通过VMware共享文件夹(简单又好用,几乎什么都不用设置)
Win7是Server,Mac是Client,VMware上运行Mac系统 1.在VMware的Options菜单中选择Shared Folders选项 2.选择Always enabled选项 3. ...
- android开发之Intent.setFlags()_让Android点击通知栏信息后返回正在运行的程序
android开发之Intent.setFlags()_让Android点击通知栏信息后返回正在运行的程序 在应用里使用了后台服务,并且在通知栏推送了消息,希望点击这个消息回到activity ...
- HDU 4836 The Query on the Tree lca || 欧拉序列 || 动态树
lca的做法还是非常明显的.简单粗暴, 只是不是正解.假设树是长链就会跪,直接变成O(n).. 最后跑的也挺快,出题人还是挺阳光的.. 动态树的解法也是听别人说能ac的.预计就是放在splay上剖分一 ...
- javascript笔记整理(对象基础)
一.名词解释 1.基于对象(一切皆对象,以对象的概念来编程) 2.面向对象编程(Object Oriented Programming,OOP) A.对象(JavaScript 中的所有事物都是对象) ...
- js ajax调用请求
<pre name="code" class="html"> function getAppList(env){ var data = {}; da ...
- 刘德华夏日Fiesta演唱会上那个表演探戈舞的演员是谁啊?_百度知道
刘德华夏日Fiesta演唱会上那个表演探戈舞的演员是谁啊?_百度知道 刘德华夏日Fiesta演唱会上那个表演探戈舞的演员是谁啊? 2008-05-28 00:04 topofhill | ...
- Python源码学习十一 一个常用的内存分配函数
void * _PyObject_DebugMallocApi(char id, size_t nbytes) { uchar *p; /* base address of malloc'ed blo ...
- XML文件解析之--DOM与SAX
xml文件又称‘可扩展性标记语言’,可以对文档和数据进行结构化处理,从而能够在部门.客户和供应商之间进行交换,实现动态内容生成,企业集成和应用开发. 我们在进行web开发的时候离不开xml文件,xml ...
- Git flow 的流程
Git flow 的流程与参考 Git flow 出自 A successful Git branching model,这里使用了一个前端项目配合本文稿实施了 git flow 并记录流程作出示 ...
- Leetcode:find_minimum_in_rotated_sorted_array
一. 题目 给定一个排好序的数组.数组可能是单调递增,也可能有一个变换. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2) 要求找出最小的数. ...