java根据isbn编码获取书籍信息(附赠http url的util包)

来源:互联网 发布:数据导入excel表格 编辑:程序博客网 时间:2024/06/03 19:16

controller代码:

    /**      * 测试     *      * */    @RequestMapping(value = "/test", method = RequestMethod.POST)    public JsonResult test() {         String url="https://api.douban.com/v2/book/isbn/:"+"9787115417305";           String result = HttpUtil.post(url, "", null, "GBK");         String url1="http://jisuisbn.market.alicloudapi.com/isbn/query?isbn="+"9787212058937";           String result1 = HttpUtil.get1(url1, null, "GBK");         Map<String, Object> map = new HashMap<>();         map.put("result", result);         map.put("result1", result1);         return new JsonResult(ResultCode.SUCCESS, "检测成功",map);    }

自定义httpUtil包:

package com.datebook.util;import java.io.IOException;import java.io.InputStream;import java.io.StringReader;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.zip.GZIPInputStream;import org.apache.http.Header;import org.apache.http.HeaderElement;import org.apache.http.HttpEntity;import org.apache.http.HttpException;import org.apache.http.HttpRequest;import org.apache.http.HttpRequestInterceptor;import org.apache.http.HttpResponse;import org.apache.http.HttpResponseInterceptor;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.params.ClientPNames;import org.apache.http.entity.HttpEntityWrapper;import org.apache.http.entity.StringEntity;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.conn.PoolingClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.params.HttpParams;import org.apache.http.protocol.HTTP;import org.apache.http.protocol.HttpContext;import org.apache.http.util.EntityUtils;public class HttpUtil {    private static HashMap<String, HttpClient> sessionMap = new HashMap<String, HttpClient>();    public HttpUtil() {    }    /*     * 将形如“\u7cfb\u7edf\u7e41\u5fd9\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5\u3002”的字符串解码     */    public static String decode(String s) {        StringReader s1 = new StringReader(s);        try {            char[] chars = new char[s.length()];            s1.read(chars);            return new String(chars);        } catch (Exception ex) {        }        return null;    }    /**     * get httpGet     *      * @param url     *            String     * @param name     *            String 连接名称,用以维护session,不需要维持连接时请置null,操作结束后请调用destroy方法     * @param charset     *            String     * @return String     */    public static String get(String url, String name, String charset) {        if (charset == null)            charset = HTTP.UTF_8;        try {            HttpClient httpclient;            if (name == null) { // 不需要维持连接                httpclient = createHttpClient();            } else if (sessionMap.containsKey(name)) {                httpclient = sessionMap.get(name);            } else {                httpclient = createHttpClient();                sessionMap.put(name, httpclient);            }            HttpGet httpget1 = new HttpGet(url);            // httpget1.addHeader("Authorization",            // "OAuth oauth_consumer_key=\"450215437\",oauth_nonce=\"SThfUW\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1386241655\",oauth_version=\"1.0\",x_auth_mode=\"client_auth\",x_auth_password=\"a77a125\",x_auth_username=\"450215437\",oauth_signature=\"2s6KCmXhuUgDAyl8gc/HMkT/dPY=\"");            HttpResponse response1 = httpclient.execute(httpget1);            HttpEntity entity1 = response1.getEntity();            return EntityUtils.toString(entity1, charset);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static String get1(String url, String name, String charset) {        if (charset == null)            charset = HTTP.UTF_8;        try {            HttpClient httpclient;            if (name == null) { // 不需要维持连接                httpclient = createHttpClient();            } else if (sessionMap.containsKey(name)) {                httpclient = sessionMap.get(name);            } else {                httpclient = createHttpClient();                sessionMap.put(name, httpclient);            }            HttpGet httpget1 = new HttpGet(url);            // httpget1.addHeader("Authorization",            // "OAuth oauth_consumer_key=\"450215437\",oauth_nonce=\"SThfUW\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1386241655\",oauth_version=\"1.0\",x_auth_mode=\"client_auth\",x_auth_password=\"a77a125\",x_auth_username=\"450215437\",oauth_signature=\"2s6KCmXhuUgDAyl8gc/HMkT/dPY=\"");            httpget1.addHeader("Authorization", "APPCODE 089d4879c794479fae61ad0784cd41c0");            HttpResponse response1 = httpclient.execute(httpget1);            HttpEntity entity1 = response1.getEntity();            return EntityUtils.toString(entity1, charset);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static String getJuhe(String url, String name, String charset) {        if (charset == null)            charset = HTTP.UTF_8;        // Hm_lvt_4d698a59cb2f4880202bc924e8364d90=1358670422;        // Hm_lpvt_4d698a59cb2f4880202bc924e8364d90=1358670433;        // PHPSESSID=r1pgkduu079mirjcdukd1s22i7        try {            HttpClient httpclient;            if (name == null) { // 不需要维持连接                httpclient = createHttpClientJuhe();            } else if (sessionMap.containsKey(name)) {                httpclient = sessionMap.get(name);            } else {                httpclient = createHttpClientJuhe();                sessionMap.put(name, httpclient);            }            HttpGet httpget1 = new HttpGet(url);            HttpResponse response1 = httpclient.execute(httpget1);            HttpEntity entity1 = response1.getEntity();            return EntityUtils.toString(entity1, charset);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    /**     * post     *      * @param url     *            String     * @param map     *            HashMap 提交表单的键值对     * @param name     *            String 连接名称,用以维护session     * @param charset     *            String     * @return String     */    public static String post(String url, HashMap<String, String> map,String name, String charset) {        if (charset == null)            charset = HTTP.UTF_8;        try {            HttpClient httpclient;            if (name == null) { // 不需要维持连接                httpclient = createHttpClient();            } else if (sessionMap.containsKey(name)) {                httpclient = sessionMap.get(name);            } else {                httpclient = createHttpClient();                sessionMap.put(name, httpclient);            }            HttpPost httpost = new HttpPost(url);//          httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);            List<NameValuePair> nvps = new ArrayList<NameValuePair>();            if (map != null) {                Iterator it = map.keySet().iterator();                while (it.hasNext()) {                    String key = (String) it.next();                    nvps.add(new BasicNameValuePair(key, map.get(key)));                }            }            httpost.setEntity(new UrlEncodedFormEntity(nvps, charset));            // System.out.println("!!!!!!!!!!!!!!!");            // long s=System.currentTimeMillis();            HttpResponse response = httpclient.execute(httpost);            // System.out.println((System.currentTimeMillis()-s)/1000);            HttpEntity entity1 = response.getEntity();            // entity1.consumeContent();            return EntityUtils.toString(entity1, charset);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static String postFile(String url, MultipartEntity entity,            String name, String charset) {        if (charset == null)            charset = HTTP.UTF_8;        try {            HttpClient httpclient;            if (name == null) { // 不需要维持连接                httpclient = createHttpClient();            } else if (sessionMap.containsKey(name)) {                httpclient = sessionMap.get(name);            } else {                httpclient = createHttpClient();                sessionMap.put(name, httpclient);            }            HttpPost httpost = new HttpPost(url);            httpost.setEntity(entity);            // System.out.println("!!!!!!!!!!!!!!!");            // long s=System.currentTimeMillis();            HttpResponse response = httpclient.execute(httpost);            // System.out.println((System.currentTimeMillis()-s)/1000);            HttpEntity entity1 = response.getEntity();            // entity1.consumeContent();            return EntityUtils.toString(entity1, charset);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static String post(String url, String content, String name,String charset) {        if (charset == null)            charset = HTTP.UTF_8;        try {            HttpClient httpclient;            if (name == null) { // 不需要维持连接                httpclient = createHttpClient();            } else if (sessionMap.containsKey(name)) {                httpclient = sessionMap.get(name);            } else {                httpclient = createHttpClient();                sessionMap.put(name, httpclient);            }            HttpPost httpost = new HttpPost(url);            if (content != null) {                httpost.setEntity(new StringEntity(content, charset));            }            HttpResponse response = httpclient.execute(httpost);            HttpEntity entity1 = response.getEntity();            // entity1.consumeContent();            return EntityUtils.toString(entity1, charset);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static String post2(String url, String content, String name,String charset) {        if (charset == null)            charset = HTTP.UTF_8;        System.out.println("-----------------post2");        try {            HttpClient httpclient;            if (name == null) { // 不需要维持连接                httpclient = createHttpClient();            } else if (sessionMap.containsKey(name)) {                httpclient = sessionMap.get(name);            } else {                httpclient = createHttpClient();                sessionMap.put(name, httpclient);            }            HttpPost httpost = new HttpPost(url);            httpost.addHeader("Accept", "*/*");            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);            if (content != null) {                httpost.setEntity(new StringEntity(content, charset));            }            System.out.println("-----------------执行开始");            System.out.println(content);            System.out.println(httpost.toString());            HttpResponse response = httpclient.execute(httpost);            System.out.println("--------------执行返回"+response.toString());            HttpEntity entity1 = response.getEntity();            // entity1.consumeContent();            return EntityUtils.toString(entity1, charset);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static void destroy(String name) {        HttpClient httpclient = sessionMap.get(name);        httpclient.getConnectionManager().shutdown();        sessionMap.remove(name);    }    private static HttpClient createHttpClient() {        DefaultHttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());        System.getProperties()                .setProperty(                        "httpclient.useragent",                        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");        try {            httpclient.addRequestInterceptor(new HttpRequestInterceptor() {                public void process(final HttpRequest request,                        final HttpContext context) throws HttpException,                        IOException {                    if (!request.containsHeader("Accept-Encoding")) {                        request.addHeader("Accept-Encoding", "gzip");                    }                }            });            httpclient.addResponseInterceptor(new HttpResponseInterceptor() {                public void process(final HttpResponse response,                        final HttpContext context) throws HttpException,                        IOException {                    HttpEntity entity = response.getEntity();                    Header ceheader = entity.getContentEncoding();                    if (ceheader != null) {                        HeaderElement[] codecs = ceheader.getElements();                        for (int i = 0; i < codecs.length; i++) {                            if (codecs[i].getName().equalsIgnoreCase("gzip")) {                                response.setEntity(new GzipDecompressingEntity(                                        response.getEntity()));                                return;                            }                        }                    }                }            });        } catch (Exception e) {            e.printStackTrace();        }        return httpclient;    }    private static HttpClient createHttpClientJuhe() {        DefaultHttpClient httpclient = new DefaultHttpClient();        System.getProperties()                .setProperty(                        "httpclient.useragent",                        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");        try {            httpclient.addRequestInterceptor(new HttpRequestInterceptor() {                public void process(final HttpRequest request,                        final HttpContext context) throws HttpException,                        IOException {                    if (!request.containsHeader("Accept-Encoding")) {                        request.addHeader("Accept-Encoding", "gzip");                    }                    request.addHeader("Referer", "http://lbs.juhe.cn/cell.php");                }            });            httpclient.addResponseInterceptor(new HttpResponseInterceptor() {                public void process(final HttpResponse response,                        final HttpContext context) throws HttpException,                        IOException {                    HttpEntity entity = response.getEntity();                    Header ceheader = entity.getContentEncoding();                    if (ceheader != null) {                        HeaderElement[] codecs = ceheader.getElements();                        for (int i = 0; i < codecs.length; i++) {                            if (codecs[i].getName().equalsIgnoreCase("gzip")) {                                response.setEntity(new GzipDecompressingEntity(                                        response.getEntity()));                                return;                            }                        }                    }                }            });        } catch (Exception e) {            e.printStackTrace();        }        return httpclient;    }    static class GzipDecompressingEntity extends HttpEntityWrapper {        public GzipDecompressingEntity(final HttpEntity entity) {            super(entity);        }        @Override        public InputStream getContent() throws IOException,                IllegalStateException {            // the wrapped entity's getContent() decides about repeatability            InputStream wrappedin = wrappedEntity.getContent();            return new GZIPInputStream(wrappedin);        }        @Override        public long getContentLength() {            // length of ungzipped content is not known            return -1;        }    }    public static String getReg(String src, String reg) {        if (src == null || reg == null)            return null;        Pattern p = Pattern.compile(reg);        Matcher m = p.matcher(src);        if (m.find()) {            return m.group(1);        }        return null;    }    public static String get(String url, String name, String charset,boolean redirect) {        if (charset == null)            charset = HTTP.UTF_8;        try {            HttpClient httpclient;            if (name == null) { // 不需要维持连接                httpclient = createHttpClient();            } else if (sessionMap.containsKey(name)) {                httpclient = sessionMap.get(name);            } else {                httpclient = createHttpClient();                sessionMap.put(name, httpclient);            }            HttpGet httpget1 = new HttpGet(url);            if (!redirect) {                HttpParams params = httpclient.getParams();                params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);                httpget1.setParams(params);            }            // httpget1.addHeader("Authorization",            // "OAuth oauth_consumer_key=\"450215437\",oauth_nonce=\"SThfUW\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1386241655\",oauth_version=\"1.0\",x_auth_mode=\"client_auth\",x_auth_password=\"a77a125\",x_auth_username=\"450215437\",oauth_signature=\"2s6KCmXhuUgDAyl8gc/HMkT/dPY=\"");            HttpResponse response1 = httpclient.execute(httpget1);            if (response1.getStatusLine() != null                    && response1.getStatusLine().toString()                            .startsWith("HTTP/1.1 30")) {                Header[] headers = response1.getHeaders("Location");                for (Header h : headers) {                    HttpEntity entity1 = response1.getEntity();                    entity1.consumeContent();                    return h.getValue();                }            }            HttpEntity entity1 = response1.getEntity();            return EntityUtils.toString(entity1, charset);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }     public static byte[] downloadFile(String url,String name){         try {             HttpClient httpclient;             if (name == null) { //不需要维持连接                 httpclient = createHttpClient();             } else if (sessionMap.containsKey(name)) {                 httpclient = sessionMap.get(name);             } else {                 httpclient = createHttpClient();                 sessionMap.put(name, httpclient);             }             HttpGet httpget1 = new HttpGet(url);//             httpget1.addHeader("Authorization", "Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; HUAWEI U8661 Build/HuaweiU8661) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");             HttpResponse response1 = httpclient.execute(httpget1);             HttpEntity entity1 = response1.getEntity();             return EntityUtils.toByteArray(entity1);//             return EntityUtils.toString(entity1, charset);         } catch (Exception e) {             e.printStackTrace();         }         return null;    }     public static String postException(String url, String content, String name,                String charset) throws Exception{            if (charset == null)                charset = HTTP.UTF_8;                HttpClient httpclient;                if (name == null) { // 不需要维持连接                    httpclient = createHttpClient();                } else if (sessionMap.containsKey(name)) {                    httpclient = sessionMap.get(name);                } else {                    httpclient = createHttpClient();                    sessionMap.put(name, httpclient);                }                HttpPost httpost = new HttpPost(url);                if (content != null) {                    httpost.setEntity(new StringEntity(content, charset));                }                HttpResponse response = httpclient.execute(httpost);                HttpEntity entity1 = response.getEntity();                return EntityUtils.toString(entity1, charset);        }}

效果图:
这里写图片描述

阅读全文
0 0
原创粉丝点击