php語言檢索各類圖書信息

書籍是人類的終生朋友,有時候要檢索個書籍啥的,一般我們都會去圖書館,但是如果自己開發一款應用,比如網站,app之類的就顯然不能這麼搞了,一般情況下很多網站都不允許數據外流的,這種情況最好就是調用專門的提供數據的接口,接着筆者就拿php語言爲例來實現圖書信息檢索這個功能,直接上代碼:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<?php

/**
 * @author 
 * @copyright 2019
 */
 
header("content-type:text/html;charset=utf-8");         //設置編碼
 
//配置您申請的appKey和openId
$app_key = "***";
$open_id = "***";

/**
$url 請求地址
$params 請求參數
$ispost 請求方法
*/

function http_curl($url,$params=false,$ispost=false){
   
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , "xiaocongjisuan");
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    
    return $response;
}

function main(){
    
    global $app_key;
    global $open_id;
    
    $domain="http://api.xiaocongjisuan.com/";
    $servlet="data/bookresource/get";
    $method="get";
    
    $url=$domain."".$servlet;
    
    $params['appKey']=$app_key;
    $params['openId']=$open_id;
    
    //變動部分
    $params["q"]="歷史";
    $params["field"]="name";
    $params["currentPage"]=1;
    $params["pageSize"]=10;
    $params["order"]="up";
    $params["sortField"]="pageNum";
    
    //編碼轉換
    foreach ($params as $key=>$value) {
        $params[$key]=mb_convert_encoding($value, "UTF-8", "GBK");
    }

    $paramstring = http_build_query($params);
    $content = http_curl($url,$paramstring,true);
    
    return $content;
}

echo main();
?>

當然java語言也可以實現,例子如下

package com.xiaocongjisuan.module.example;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class Application {
    
     public static final String DEF_CHATSET = "UTF-8";
     public static final int DEF_CONN_TIMEOUT = 30000;
     public static final int DEF_READ_TIMEOUT = 30000;
     public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
     
     //配置您申請的appKey和openId
     public static final String APP_KEY ="yours";
     public static final String OPEN_ID ="yours";
     
     //將map型轉爲請求參數型
     public static String urlEncode(Map<String,Object> params) {
        
        if(params==null){return "";};
         
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String,Object> i : params.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String r=sb.toString();
        if(r.endsWith("&")){
            r = r.substring(0,r.length()-1);
        }
        return r;
     }
     
     /**
     *
     * @param requestUrl 請求地址
     * @param params 請求參數
     * @param method 請求方法
     * @return 請求結果
     * @throws Exception
     */
     public static String requestContent(String requestUrl, Map<String,Object> params,String method) throws Exception {
        
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {

            //組裝請求鏈接
            StringBuffer sb = new StringBuffer();
            
            if(method!=null&&method.equalsIgnoreCase("get")){
                requestUrl = requestUrl+"?"+urlEncode(params);
            }

            //默認get
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            
            if(method!=null&&method.equalsIgnoreCase("post")){
                 conn.setRequestMethod("POST");
                 conn.setDoOutput(true);
                 conn.setDoInput(true);
            }

            //參數配置
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            
            if (params!= null && method.equalsIgnoreCase("post")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlEncode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            
            //讀取數據
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
    
    
    public static void main(String[] args) throws Exception{
        
        String domain="http://api.xiaocongjisuan.com/";
        String servlet="data/bookresource/get";
        String method="get";
        
        String requestUrl=domain+servlet;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("appKey",APP_KEY);
        params.put("openId",OPEN_ID);

        //變動部分
        params.put("q","歷史");
        params.put("field","name");
        params.put("currentPage",1);
        params.put("pageSize",10);
        params.put("order","up");
        params.put("sortField","pageNum");
        
        
        String result=requestContent(requestUrl,params,method);
        System.out.println(result);
    }
}

其他語言的實現方式可以參看這篇帖子

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章