`

Java模拟HTTP的Get和Post请求(增强)

 
阅读更多
在之前,写了篇Java模拟HTTP的Get和Post请求的文章,这篇文章起源与和一个朋友砍飞信敏感词网站的问题,于是动用了Apache的comments-net包,也实现了get和post的http请求,并且将响应html代码获取。可是细心的博友提出:在获取有些网站出现乱码,最后发现没有处理字符集,这里做针对博友的意见做了增强,增强部分主要是响应内容的字符编码、相应代码的美化选项。
 
下面是代码:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
* HTTP工具箱
*
* @author leizhimin 2009-6-19 16:36:18
*/

public final class HttpTookit {
        private static Log log = LogFactory.getLog(HttpTookit.class);

        /**
         * 执行一个HTTP GET请求,返回请求响应的HTML
         *
         * @param url                 请求的URL地址
         * @param queryString 请求的查询参数,可以为null
         * @param charset         字符集
         * @param pretty            是否美化
         * @return 返回请求响应的HTML
         */

        public static String doGet(String url, String queryString, String charset, boolean pretty) {
                StringBuffer response = new StringBuffer();
                HttpClient client = new HttpClient();
                HttpMethod method = new GetMethod(url);
                try {
                        if (StringUtils.isNotBlank(queryString))
                                //对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串
                                method.setQueryString(URIUtil.encodeQuery(queryString));
                        client.executeMethod(method);
                        if (method.getStatusCode() == HttpStatus.SC_OK) {
                                BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
                                String line;
                                while ((line = reader.readLine()) != null) {
                                        if (pretty)
                                                response.append(line).append(System.getProperty("line.separator"));
                                        else
                                                response.append(line);
                                }
                                reader.close();
                        }
                } catch (URIException e) {
                        log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
                } catch (IOException e) {
                        log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
                } finally {
                        method.releaseConnection();
                }
                return response.toString();
        }

        /**
         * 执行一个HTTP POST请求,返回请求响应的HTML
         *
         * @param url         请求的URL地址
         * @param params    请求的查询参数,可以为null
         * @param charset 字符集
         * @param pretty    是否美化
         * @return 返回请求响应的HTML
         */

        public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {
                StringBuffer response = new StringBuffer();
                HttpClient client = new HttpClient();
                HttpMethod method = new PostMethod(url);
                //设置Http Post数据
                if (params != null) {
                        HttpMethodParams p = new HttpMethodParams();
                        for (Map.Entry<String, String> entry : params.entrySet()) {
                                p.setParameter(entry.getKey(), entry.getValue());
                        }
                        method.setParams(p);
                }
                try {
                        client.executeMethod(method);
                        if (method.getStatusCode() == HttpStatus.SC_OK) {
                                BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
                                String line;
                                while ((line = reader.readLine()) != null) {
                                        if (pretty)
                                                response.append(line).append(System.getProperty("line.separator"));
                                        else
                                                response.append(line);
                                }
                                reader.close();
                        }
                } catch (IOException e) {
                        log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
                } finally {
                        method.releaseConnection();
                }
                return response.toString();
        }

        public static void main(String[] args) {
                String y = doGet("http://video.sina.com.cn/life/tips.html", null, "GBK", true);
                System.out.println(y);
        }
}
 
其实,这里的美化加入系统平台无关的换行符,可以任何平台上正确显示换行。
 
另外发现,通过JDK自带类库实现的请求,往往在请求一些url时,无法获取到请求结果。但此工具总能保证只要你的浏览器能打开,它总能忠实的将响应的内容反馈回来。
 
另外,将查看Java平台环境的代码给出来,很常用!
        public static void main(String[] args) {
                Properties p = System.getProperties();
                for (Map.Entry<Object, Object> entry : p.entrySet()) {
                        System.out.println(entry.getKey() + " = " + entry.getValue());
                }
        }
 
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = Q:\jdk6\jre\bin
java.vm.version = 14.0-b16
java.vm.vendor = Sun Microsystems Inc.
java.vendor.url = http://java.sun.com/
path.separator = ;
idea.launcher.port = 7540
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
sun.java.launcher = SUN_STANDARD
user.country = CN
sun.os.patch.level = Service Pack 3
java.vm.specification.name = Java Virtual Machine Specification
user.dir = E:\NVMS\Code\sinamovie
java.runtime.version = 1.6.0_14-b08
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = Q:\jdk6\jre\lib\endorsed
os.arch = x86
java.io.tmpdir = C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
line.separator =    

java.vm.specification.vendor = Sun Microsystems Inc.
user.variant =    
os.name = Windows XP
sun.jnu.encoding = GBK
java.library.path = Q:\jdk6\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;Q:\JavaFX\javafx-sdk1.2\bin;Q:\JavaFX\javafx-sdk1.2\emulator\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\StormII\Codec;C:\Program Files\StormII
java.specification.name = Java Platform API Specification
java.class.version = 50.0
sun.management.compiler = HotSpot Client Compiler
os.version = 5.1
user.home = d:\我的文档
user.timezone = Asia/Shanghai
java.awt.printerjob = sun.awt.windows.WPrinterJob
idea.launcher.bin.path = C:\IDEA8\bin
file.encoding = UTF-8
java.specification.version = 1.6
java.class.path = Q:\jdk6\jre\lib\alt-rt.jar;Q:\jdk6\jre\lib\charsets.jar;Q:\jdk6\jre\lib\deploy.jar;Q:\jdk6\jre\lib\javaws.jar;Q:\jdk6\jre\lib\jce.jar;Q:\jdk6\jre\lib\jsse.jar;Q:\jdk6\jre\lib\management-agent.jar;Q:\jdk6\jre\lib\plugin.jar;Q:\jdk6\jre\lib\resources.jar;Q:\jdk6\jre\lib\rt.jar;Q:\jdk6\jre\lib\ext\dnsns.jar;Q:\jdk6\jre\lib\ext\localedata.jar;Q:\jdk6\jre\lib\ext\sunjce_provider.jar;Q:\jdk6\jre\lib\ext\sunmscapi.jar;Q:\jdk6\jre\lib\ext\sunpkcs11.jar;E:\NVMS\Code\sinamovie\out\production\sinamovie;E:\NVMS\Code\sinamovie\lib\jlm\ezmorph-1.0.4.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-fileupload.jar;E:\NVMS\Code\sinamovie\lib\jotm\jotm-jms.jar;E:\NVMS\Code\sinamovie\lib\jotm\jotm-datasource.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-codec.jar;E:\NVMS\Code\sinamovie\lib\spring-jdbc.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-dbcp.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-httpclient.jar;E:\NVMS\Code\sinamovie\lib\junit\junit-3.8.2.jar;E:\NVMS\Code\sinamovie\lib\log4j\log4j-1.2.15.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-beanutils.jar;E:\NVMS\Code\sinamovie\lib\aspectjrt.jar;E:\NVMS\Code\sinamovie\lib\spring-orm.jar;E:\NVMS\Code\sinamovie\lib\jotm\jotm-client.jar;E:\NVMS\Code\sinamovie\lib\simple-xml\stax-1.2.0.jar;E:\NVMS\Code\sinamovie\lib\jotm\jotm-core.jar;E:\NVMS\Code\sinamovie\lib\spring-beans.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-digester.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-logging.jar;E:\NVMS\Code\sinamovie\lib\aspectjweaver.jar;E:\NVMS\Code\sinamovie\lib\jotm\xapool.jar;E:\NVMS\Code\sinamovie\lib\spring-aop.jar;E:\NVMS\Code\sinamovie\lib\jlm\json.jar;E:\NVMS\Code\sinamovie\lib\jlm\proxool-cglib.jar;E:\NVMS\Code\sinamovie\lib\jlm\proxool-0.9.1.jar;E:\NVMS\Code\sinamovie\lib\mysql-connector-java-5.1.6-bin.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-io.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-validator.jar;E:\NVMS\Code\sinamovie\lib\asm-util-2.2.3.jar;E:\NVMS\Code\sinamovie\lib\spring-core.jar;E:\NVMS\Code\sinamovie\lib\jlm\oscache-2.4.1.jar;E:\NVMS\Code\sinamovie\lib\spring-context.jar;E:\NVMS\Code\sinamovie\lib\ibatis\ibatis-2.3.4.726.jar;E:\NVMS\Code\sinamovie\lib\aopalliance.jar;E:\NVMS\Code\sinamovie\lib\dom4j\dom4j-1.6.1.jar;E:\NVMS\Code\sinamovie\lib\jlm\htmlparser.jar;E:\NVMS\Code\sinamovie\lib\jlm\json-lib-2.2.1-jdk15.jar;E:\NVMS\Code\sinamovie\lib\spring-jms.jar;E:\NVMS\Code\sinamovie\lib\jlm\flexjson.jar;E:\NVMS\Code\sinamovie\lib\cglib-nodep-2.1_3.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-collections.jar;E:\NVMS\Code\sinamovie\lib\jotm\jotm-standalone.jar;E:\NVMS\Code\sinamovie\lib\jlm\jeval.jar;E:\NVMS\Code\sinamovie\lib\asm-commons-2.2.3.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-attributes-compiler.jar;E:\NVMS\Code\sinamovie\lib\spring-tx.jar;E:\NVMS\Code\sinamovie\lib\junit\junit-4.4.jar;E:\NVMS\Code\sinamovie\lib\jotm\ow2-jta-1.1-spec.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-attributes-api.jar;E:\NVMS\Code\sinamovie\lib\spring-context-support.jar;E:\NVMS\Code\sinamovie\lib\simple-xml\stax-api-1.0.1.jar;E:\NVMS\Code\sinamovie\lib\dom4j\jaxen-1.1-beta-7.jar;E:\NVMS\Code\sinamovie\lib\simple-xml\simple-xml-2.0.2.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-lang.jar;E:\NVMS\Code\sinamovie\lib\asm-2.2.3.jar;E:\NVMS\Code\sinamovie\lib\spring-test.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-discovery.jar;E:\NVMS\Code\sinamovie\lib\jlm\htmllexer.jar;E:\NVMS\Code\sinamovie\lib\jakarta-commons\commons-pool.jar;C:\IDEA8\lib\idea_rt.jar
user.name = Administrator
java.vm.specification.version = 1.0
java.home = Q:\jdk6\jre
sun.arch.data.model = 32
user.language = zh
java.specification.vendor = Sun Microsystems Inc.
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode, sharing
java.version = 1.6.0_14
java.ext.dirs = Q:\jdk6\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
sun.boot.class.path = Q:\jdk6\jre\lib\resources.jar;Q:\jdk6\jre\lib\rt.jar;Q:\jdk6\jre\lib\sunrsasign.jar;Q:\jdk6\jre\lib\jsse.jar;Q:\jdk6\jre\lib\jce.jar;Q:\jdk6\jre\lib\charsets.jar;Q:\jdk6\jre\classes
java.vendor = Sun Microsystems Inc.
file.separator = \
java.vendor.url.bug = http://java.sun.com/cgi-bin/bugreport.cgi
sun.io.unicode.encoding = UnicodeLittle
sun.cpu.endian = little
sun.desktop = windows
sun.cpu.isalist =    

Process finished with exit code 0
 
再次感谢细心博友的宝贵意见,让此工具变得更完善,更好用!
 

本文出自 “熔 岩” 博客 http://lavasoft.blog.51cto.com/62575/175911/

分享到:
评论

相关推荐

    后台模拟发送GET和POST请求

    使用HttpClient模拟GET和POST请求,主要涉及以下几个步骤: 1. 创建HttpClient实例:这是所有操作的基础,通过`HttpClientBuilder`或`HttpClients`类可以创建HttpClient对象。 ```java CloseableHttpClient ...

    java HttpClient 发送GET请求和带有表单参数的POST请求教程例子

    ### Java HttpClient 发送GET请求和带有表单参数的POST请求详解 #### 一、概述 在Java编程中,处理HTTP请求是一项常见的需求,特别是在与Web服务进行交互时。Apache HttpClient库提供了一种强大的方法来执行HTTP...

    Java模拟HTTP的Get和Post请求

    NULL 博文链接:https://xieke90.iteye.com/blog/2259953

    HttpClient模拟get,post请求并发送请求参数(json等)

    它允许开发者模拟GET和POST等HTTP请求,并可以方便地发送JSON等数据作为请求参数。在本文中,我们将深入探讨如何使用HttpClient进行HTTP请求操作,以及如何处理JSON数据。 首先,我们需要引入HttpClient的相关依赖...

    Java 模拟Ajax POST GET 提交代码

    Java 模拟Ajax POST GET 提交代码,实测很好用。

    java 发送get ,post请求,高效便捷,并发性强,原生代码

    java发送get,post请求,可以实现与后台交互,代码便捷高效,是原生代码,支持并发性;代码结构清晰易懂,容易上手;

    Java发送post,get请求

    java模拟HTTP发送post和get请求工具类,使用httpClient类

    java后台实现 get post 提交.zip

    以上代码展示了如何在Java后台实现GET和POST请求的基本过程。在实际应用中,我们通常会使用框架如Spring MVC,它提供了更高级的抽象,使得处理HTTP请求变得更加便捷。Spring MVC允许我们定义控制器方法,这些方法...

    《转》Java模拟HTTP的Get和Post请求

    NULL 博文链接:https://tujunlan.iteye.com/blog/1997745

    JAVA-用HttpClient来模拟浏览器GET,POST.docx

    JAVA使用HttpClient模拟浏览器GET、POST请求 在本文中,我们将介绍如何使用Apache Commons HttpClient库来模拟浏览器的GET和POST请求。HttpClient库是一个开放源码的项目,是Apache Commons项目的一部分,旨在简化...

    (完整版)JAVA利用HttpClient进行POST请求(HTTPS).doc

    在示例代码中,我们使用HttpGet对象来发送POST请求,并指定请求的URL、请求头和请求体。 使用HttpClient发送POST请求可以帮助我们与HTTPS服务器进行交互,但需要注意证书验证过程。使用X509TrustManager可以忽略...

    service_java接口远程调用_get、post、带参数远程调用_

    可以使用`HttpURLConnection`或`HttpClient`模拟POST请求,但设置请求方法为GET: ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); ...

    HttpUtils Java get post 工具类

    "HttpUtils Java get post 工具类" 提供了便捷的方法来发送GET和POST请求,简化了网络请求的操作。以下是对这两个主要HTTP方法的详细解释以及如何在Java中实现它们。 **1. GET方法** GET是HTTP中最常见的请求方法,...

    java后端请求HTTP需要用到的jar包及其测试方法(get和post)

    测试过程中,可以使用JUnit或其他测试框架来编写单元测试,模拟不同的请求场景,确保HTTP请求能正确发送和接收。测试内容应包括但不限于:正常请求、错误处理、超时设置、连接管理、异步请求等。 总结来说,利用...

    使用Java模拟http请求.rar

    Java作为一种多用途的编程语言,提供了丰富的库来帮助开发者模拟HTTP请求,使得我们可以在程序中实现与服务器的交互,比如发送GET、POST请求,获取网页数据,甚至进行文件上传等操作。本教程将详细讲解如何使用Java...

    java http 发送 put delete post get请求

    是一个Java 发送http put、delete、 post、 get 请求的工具类。可用在与restful service 进行通讯的代码中。

    Java模拟get/post登陆(含验证码)

    本篇文章将深入探讨如何使用Java模拟GET/POST登录,特别是涉及验证码处理的情况。我们将主要关注Httpclient库的使用,以及可能涉及到的图像识别技术(OCR)。 首先,让我们了解一下HTTP的基本概念。HTTP是超文本...

    JAVA模拟网页发送请求

    本文详细介绍了如何使用Java模拟发送GET和POST请求,并对Cookie进行了处理。掌握了这些技术后,你就可以更灵活地与Web服务交互,实现自动化任务或数据抓取等功能。需要注意的是,在实际应用中还应考虑异常处理、编码...

    java 作为客户端发送http post请求登录网站首页。

    通过理解HTTP协议、状态码和客户端库的使用,我们可以有效地解决登录页面自动跳转的问题,从而成功地使用Java作为客户端发送HTTP POST请求登录网站首页。在实践中,还需要注意安全性问题,比如使用HTTPS加密通信,...

Global site tag (gtag.js) - Google Analytics