写了一下午,借鉴apache的 httpclient 源码 调用 写的,拿出来分享一下,可以用作其他不同平台的项目post/get数据上面。

package cn.shb.test;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; /**
* Created by caozengling on 2016/9/27.
*/
public class ZhuanLiSearch {
//超时间隔
private static int connectTimeOut = 60000;
//让connectionmanager管理httpclientconnection时是否关闭连接
public static boolean alwaysClose = false;
//返回数据编码格式
private String encoding = "UTF-8"; private final HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); public HttpClient getHttpClient() {
return client;
} /**
* 用法:
* HttpRequestProxy hrp = new HttpRequestProxy();
* hrp.doRequest("http://www.163.com",null,null,"gbk");
*
* @param url 请求的资源URL
* @param postData POST请求时form表单封装的数据 没有时传null
* @param header request请求时附带的头信息(header) 没有时传null
* @param encoding response返回的信息编码格式 没有时传null
* @return response返回的文本数据
* @throws //CustomException
*/
public String doRequest(String url, Map postData, Map header, String encoding) throws Exception {
String responseString = null;
//头部请求信息
Header[] headers = null;
if (header != null) {
Set entrySet = header.entrySet();
int dataLength = entrySet.size();
headers = new Header[dataLength];
int i = 0;
for (Iterator itor = entrySet.iterator(); itor.hasNext(); ) {
Map.Entry entry = (Map.Entry) itor.next();
headers[i++] = new Header(entry.getKey().toString(), entry.getValue().toString());
}
}
//post方式
if (postData != null) {
PostMethod postRequest = new PostMethod(url.trim());
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
postRequest.setRequestHeader(headers[i]);
}
}
Set entrySet = postData.entrySet();
int dataLength = entrySet.size();
NameValuePair[] params = new NameValuePair[dataLength];
int i = 0;
for (Iterator itor = entrySet.iterator(); itor.hasNext(); ) {
Map.Entry entry = (Map.Entry) itor.next();
params[i++] = new NameValuePair(entry.getKey().toString(), entry.getValue().toString());
}
postRequest.setRequestBody(params);
try {
responseString = this.executeMethod(postRequest, encoding);
} catch (Exception e) { } finally {
postRequest.releaseConnection();
}
}
//get方式
if (postData == null) {
GetMethod getRequest = new GetMethod(url.trim());
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
getRequest.setRequestHeader(headers[i]);
}
}
try {
responseString = this.executeMethod(getRequest, encoding);
} catch (Exception e) { } finally {
getRequest.releaseConnection();
}
} return responseString;
} private String executeMethod(HttpMethod request, String encoding) throws Exception {
String responseContent = null;
InputStream responseStream = null;
BufferedReader rd = null;
try {
this.getHttpClient().executeMethod(request);
if (encoding != null) {
responseStream = request.getResponseBodyAsStream();
rd = new BufferedReader(new InputStreamReader(responseStream,
encoding));
String tempLine = rd.readLine();
StringBuffer tempStr = new StringBuffer();
String crlf = System.getProperty("line.separator");
while (tempLine != null) {
tempStr.append(tempLine);
tempStr.append(crlf);
tempLine = rd.readLine();
}
responseContent = tempStr.toString();
} else
responseContent = request.getResponseBodyAsString(); Header locationHeader = request.getResponseHeader("location");
//返回代码为302,301时,表示页面己经重定向,则重新请求location的url,这在
//一些登录授权取cookie时很重要
if (locationHeader != null) {
String redirectUrl = locationHeader.getValue();
this.doRequest(redirectUrl, null, null, null);
}
} catch (HttpException e) { } catch (IOException e) { } finally {
if (rd != null)
try {
rd.close();
} catch (IOException e) { }
if (responseStream != null)
try {
responseStream.close();
} catch (IOException e) { }
}
return responseContent;
} /**
* 特殊请求数据,这样的请求往往会出现redirect本身而出现递归死循环重定向
* 所以单独写成一个请求方法
* 比如现在请求的url为:http://localhost:8080/demo/index.jsp
* 返回代码为302 头部信息中location值为:http://localhost:8083/demo/index.jsp
* 这时httpclient认为进入递归死循环重定向,抛出CircularRedirectException异常
*
* @param url
* @return
* @throws //CustomException
*/
public String doSpecialRequest(String url, int count, String encoding) throws Exception {
String str = null;
InputStream responseStream = null;
BufferedReader rd = null;
GetMethod getRequest = new GetMethod(url);
//关闭httpclient自动重定向动能
getRequest.setFollowRedirects(false);
try { this.client.executeMethod(getRequest);
Header header = getRequest.getResponseHeader("location");
if (header != null) {
//请求重定向后的URL,count同时加1
this.doSpecialRequest(header.getValue(), count + 1, encoding);
}
//这里用count作为标志位,当count为0时才返回请求的URL文本,
//这样就可以忽略所有的递归重定向时返回文本流操作,提高性能
if (count == 0) {
getRequest = new GetMethod(url);
getRequest.setFollowRedirects(false);
this.client.executeMethod(getRequest);
responseStream = getRequest.getResponseBodyAsStream();
rd = new BufferedReader(new InputStreamReader(responseStream,
encoding));
String tempLine = rd.readLine();
StringBuffer tempStr = new StringBuffer();
String crlf = System.getProperty("line.separator");
while (tempLine != null) {
tempStr.append(tempLine);
tempStr.append(crlf);
tempLine = rd.readLine();
}
str = tempStr.toString();
} } catch (HttpException e) { } catch (IOException e) { } finally {
getRequest.releaseConnection();
if (rd != null)
try {
rd.close();
} catch (IOException e) { }
if (responseStream != null)
try {
responseStream.close();
} catch (IOException e) { }
}
return str;
} public static void main(String[] args) throws Exception {
ZhuanLiSearch hrp = new ZhuanLiSearch ();
Map header = new HashMap();
header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)"); Map params = new HashMap(); params.put("wd", "zhang");
StringBuffer sb = new StringBuffer();
sb.append("23200820137723.6");
String str = hrp.doRequest(
"http://www.soopat.com/Home/Result?SearchWord=" +
sb,
null, header, null);
System.out.println(str);
if (str.indexOf("NotFoundContent")!=-1){
System.out.println("1");
}else {
System.out.println("2");
}
// System.out.println(str.contains("</title>"));
// System.out.println(str);
} }

  

一个国家专利查询demo的更多相关文章

  1. 我的第一个 react redux demo

    最近学习react redux,先前看过了几本书和一些博客之类的,感觉还不错,比如<深入浅出react和redux>,<React全栈++Redux+Flux+webpack+Bab ...

  2. 1.类的加载机制_继承类的加载(一个小的Demo)说明

    今天我们先来一个小的Demo来了解类的加载顺序. public class ClassLoaderTest { public static void main(String[] args) { Sys ...

  3. 第一个ajax小demo

    第一个ajax小demo 文章来源:http://blog.csdn.net/magi1201/article/details/44569657

  4. 无废话WCF入门教程六[一个简单的Demo]

    一.前言 前面的几个章节介绍了很多理论基础,如:什么是WCF.WCF中的A.B.C.WCF的传输模式.本文从零开始和大家一起写一个小的WCF应用程序Demo. 大多框架的学习都是从增.删.改.查开始来 ...

  5. 一起来花5分钟写一个PHP入门Demo

    最近公司招了几个应届毕业生,他们对前端的了解还挺多,但是对后端的技术一无所知,我觉得,作为一个前端攻城狮,如果你有远大的抱负,就应该雨露均沾... 今天我就跟大家讲一讲PHP最基本的入门,至少别人问起 ...

  6. 使用angular.js开发的一个简易todo demo

    前沿 在CVTE实习考察的一周里,接触到了angular,并在最后的一天任务里要求使用angular做一个功能主要包括创建.编辑.恢复.删除以及留言的todo demo,并支持响应式布局.因为之前没怎 ...

  7. [iOS基础控件 - 6.10.2] PickerView 自定义row内容 国家选择Demo

    A.需求 1.自定义一个UIView和xib,包含国家名和国旗显示 2.学习row的重用   B.实现步骤 1.准备plist文件和国旗图片     2.创建模型 // // Flag.h // Co ...

  8. 他的第一个NDK的Demo

    DEMO下载链接: http://download.csdn.net/detail/logicsboy/7535409 首先给你们恶补下啥是NDK:(我从百度Copy的) NDK全称:Native D ...

  9. [小北De编程手记] Lesson 01 - AutoFramework构建 之 从一个简单的Demo聊起

    写在最前面 这个系列的主旨是要跟大家分享一下关于自动化测试框架的构建的一些心得.这几年,做了一些自动化测试框架以及团队的构建的工作.过程中遇到了很多这样的同学,他们在学习了某一门语言和一些自动化测试的 ...

随机推荐

  1. Caliburn.Micro学习笔记(四)----IHandle<T>实现多语言功能

    Caliburn.Micro学习笔记目录 说一下IHandle<T>实现多语言功能 因为Caliburn.Micro是基于MvvM的UI与codebehind分离, binding可以是双 ...

  2. SQLite剖析之临时文件、内存数据库

    一.7种临时文件    SQLite中,一个数据库由单个磁盘文件构成,简化了SQLite的使用,因为移动或备份数据库只要拷贝单个文件即可.这也使得SQLite适合用作应用程序文件格式.但是,当在单个文 ...

  3. redis-介绍与比较

    <一>. NoSQL简介:    NoSQL是Not-Only-SQL的缩写,是被设计用来替换传统的关系型数据库在某些领域的用,特别针对web2.0站点以及大型的SNS网站,用来满足高并发 ...

  4. iOS播放器 - AVPlayer

    之前有说到在播放器中一点点小技巧,现在正式记录一下AVPlayer. 这里主要是说明用AVPlayer做音乐播放器的功能实现,所以不介绍AVPlayer中那个图层类. 首先我们要声明一下播放器,这里有 ...

  5. python对Mysql操作和使用ORM框架(SQLAlchemy)

    python对mysql的操作 Mysql 常见操作 数据库操作 创建数据库 create database fuzjtest 删除数据库 drop database fuzjtest 查询数据库 s ...

  6. for循环递归树

    protected string _menu = string.Empty; public void FirstAnsyData() { try { // List<object> lsN ...

  7. 英文写作——冠词的使用(Use 0f Articles)

    1.使用'a','an','the'和不使用冠词的基本规则: <1>泛指,不可数名词不能有任何冠词 <2>泛指,可数,复数名词前不能有冠词 <3>泛指,可数,单数名 ...

  8. arguments

    arguments 转数组 通常使用下面的方法来将 arguments 转换成数组: Array.prototype.slice.call(arguments); 还有一个更简短的写法: [].sli ...

  9. 浅谈 PHP 与手机 APP 开发(API 接口开发) -- 转载

    转载自:http://www.thinkphp.cn/topic/5023.html 这个帖子写给不太了解PHP与API开发的人 一.先简单回答两个问题: 1.PHP 可以开发客户端? 答:不可以,因 ...

  10. [NHibernate]N+1 Select查询问题分析

    目录 写在前面 文档与系列文章 N+1 Select查询问题分析 总结 写在前面 在前面的文章(延迟加载,立即加载)中都提到了N+1 Select的问题,总觉得理解的很不到位,也请大家原谅,这也是为什 ...