eoLinker-API_Shop_猫咪大全_API接口_Java调用示例代码

合集下载

eoLinker-API_Shop_POI检索_API接口_C#调用示例代码

eoLinker-API_Shop_POI检索_API接口_C#调用示例代码

eoLinker-API Shop POI检索 C#调用示例代码POI检索通过关键词查询在某个地区的POI信息,支持市级、区县级查询:比如在广州查询“银行”,接口将会输出所有银行的地理信息列表。

该产品拥有以下APIs:1.POI搜索2.周边POI搜索3.POI多边形搜索注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=97申请API服务1.POI搜索using System;using System.Collections.Generic;using System.IO;using ;using System.Text;using System.Web.Script.Serialization;namespace apishop_sdk{class Program{/*** 转发请求到目的主机* @param method string 请求方法* @param url string 请求地址* @param params Dictionary<string,string> 请求参数* @param headers Dictionary<string,string> 请求头* @return string**/static string apishop_send_request(string method, string url, D ictionary<string, string> param, Dictionary<string, string> headers){string result = string.Empty;try{string paramData = "";if (param != null && param.Count > 0){StringBuilder sbuilder = new StringBuilder();foreach (var item in param){if (sbuilder.Length > 0){sbuilder.Append("&");}sbuilder.Append(item.Key + "=" + item.Value);}paramData = sbuilder.ToString();}method = method.ToUpper();if (method == "GET"){url = string.Format("{0}?{1}", url, paramData);}HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.C reate(url);if (method == "GET"){wbRequest.Method = "GET";}else if (method == "POST"){wbRequest.Method = "POST";wbRequest.ContentType = "application/x-www-form-url encoded";wbRequest.ContentLength = Encoding.UTF8.GetByteCoun t(paramData);using (Stream requestStream = wbRequest.GetRequestS tream()){using (StreamWriter swrite = new StreamWriter(r equestStream)){swrite.Write(paramData);}}}HttpWebResponse wbResponse = (HttpWebResponse)wbRequest. GetResponse();using (Stream responseStream = wbResponse.GetResponseSt ream()){using (StreamReader sread = new StreamReader(respon seStream)){result = sread.ReadToEnd();}}}catch{return "";}return result;}class Response{public string statusCode;}static void Main(string[] args){string method = "POST";string url = "https:///common/POI/queryPOI";Dictionary<string, string> param = new Dictionary<string, s tring>();param.Add("keyWords", ""); //查询关键字(规则:多个关键字用“|”分割若不指定city,并且搜索的为泛词(例如“美食”)的情况下,返回的内容为城市列表以及此城市内有多少结果符合要求。

eoLinker-API_Shop_驾考题库(所有车型)_API接口_Java调用示例代码

eoLinker-API_Shop_驾考题库(所有车型)_API接口_Java调用示例代码

eoLinker-API Shop 驾考题库-新 Java调用示例代码驾考题库-新公安部最新驾照考试题库,分科目一与科目二两种题型;包括小车、货车、客车与摩托车四类车型,涵盖C1、C2、A1、A2、A3、B1、B2、D、E、F等驾照类型。

该产品拥有以下APIs:1.获取题目信息2.获取驾考题库列表3.关键字获取题目注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=187申请API服务1.获取题目信息package net.apishop.www.controller;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLEncoder;import java.util.HashMap;import java.util.Map;import com.alibaba.fastjson.JSONObject;/*** httpUrlConnection访问远程接口工具*/public class Api{/*** 方法体说明:向远程接口发起请求,返回字节流类型结果* param url 接口地址* param requestMethod 请求方式* param params 传递参数重点:参数值需要用Base64进行转码* return InputStream 返回结果*/public static InputStream httpRequestToStream(String url, String requestMethod, Map<String, String> params){InputStream is = null;try{String parameters = "";boolean hasParams = false;// 将参数集合拼接成特定格式,如name=zhangsan&age=24for (String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");parameters += key + "=" + value + "&";hasParams = true;}if (hasParams){parameters = parameters.substring(0, parameters.length() - 1);}// 请求方式是否为getboolean isGet = "get".equalsIgnoreCase(requestMethod);// 请求方式是否为postboolean isPost = "post".equalsIgnoreCase(requestMethod);if (isGet){url += "?" + parameters;}URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnecti on();// 请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Con tent-Type为“”空)conn.setRequestProperty("Content-Type", "application/octet-stream");// conn.setRequestProperty("Content-Type", "application/x-w ww-form-urlencoded");// 设置连接超时时间conn.setConnectTimeout(50000);// 设置读取返回内容超时时间conn.setReadTimeout(50000);// 设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认falseif (isPost){conn.setDoOutput(true);}// 设置从HttpURLConnection对象读入,默认为trueconn.setDoInput(true);// 设置是否使用缓存,post方式不能使用缓存if (isPost){conn.setUseCaches(false);}// 设置请求方式,默认为GETconn.setRequestMethod(requestMethod);// post方式需要将传递的参数输出到conn对象中if (isPost){DataOutputStream dos = new DataOutputStream(conn.getOut putStream());dos.writeBytes(parameters);dos.flush();dos.close();}// 从HttpURLConnection对象中读取响应的消息// 执行该语句时才正式发起请求is = conn.getInputStream();}catch(UnsupportedEncodingException e){e.printStackTrace();}catch(MalformedURLException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}return is;}public static void main(String args[]){String url = "https:///common/postcode/getPostCo deByAddr";String requestMethod = "POST";Map<String, String> params = new HashMap<String, String>(); params.put("apiKey","your_api_key"); //需要从获取params.put("questionID", ""); //题目ID,从“获取驾考题目信息”API 获取String result = null;try{InputStream is = httpRequestToStream(url, requestMethod, pa rams);byte[] b = new byte[is.available()];is.read(b);result = new String(b);}catch(IOException e){e.printStackTrace();}if (result != null){JSONObject jsonObject = JSONObject.parseObject(result);String status_code = jsonObject.getString("statusCode");if (status_code == "000000"){// 状态码为000000, 说明请求成功System.out.println("请求成功:" + jsonObject.getString("resu lt"));}else{// 状态码非000000, 说明请求失败System.out.println("请求失败:" + jsonObject.getString("desc "));}}else{// 返回内容异常,发送请求失败,以下可根据业务逻辑自行修改System.out.println("发送请求失败");}}}2.获取驾考题库列表package net.apishop.www.controller;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLEncoder;import java.util.HashMap;import java.util.Map;import com.alibaba.fastjson.JSONObject;/*** httpUrlConnection访问远程接口工具*/public class Api{/*** 方法体说明:向远程接口发起请求,返回字节流类型结果* param url 接口地址* param requestMethod 请求方式* param params 传递参数重点:参数值需要用Base64进行转码* return InputStream 返回结果*/public static InputStream httpRequestToStream(String url, String re questMethod, Map<String, String> params){InputStream is = null;try{String parameters = "";boolean hasParams = false;// 将参数集合拼接成特定格式,如name=zhangsan&age=24for (String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");parameters += key + "=" + value + "&";hasParams = true;}if (hasParams){parameters = parameters.substring(0, parameters.length() - 1);}// 请求方式是否为getboolean isGet = "get".equalsIgnoreCase(requestMethod);// 请求方式是否为postboolean isPost = "post".equalsIgnoreCase(requestMethod);if (isGet){url += "?" + parameters;}URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnecti on();// 请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Con tent-Type为“”空)conn.setRequestProperty("Content-Type", "application/octet-stream");// conn.setRequestProperty("Content-Type", "application/x-w ww-form-urlencoded");// 设置连接超时时间conn.setConnectTimeout(50000);// 设置读取返回内容超时时间conn.setReadTimeout(50000);// 设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认falseif (isPost){conn.setDoOutput(true);}// 设置从HttpURLConnection对象读入,默认为trueconn.setDoInput(true);// 设置是否使用缓存,post方式不能使用缓存if (isPost){conn.setUseCaches(false);}// 设置请求方式,默认为GETconn.setRequestMethod(requestMethod);// post方式需要将传递的参数输出到conn对象中if (isPost){DataOutputStream dos = new DataOutputStream(conn.getOut putStream());dos.writeBytes(parameters);dos.flush();dos.close();}// 从HttpURLConnection对象中读取响应的消息// 执行该语句时才正式发起请求is = conn.getInputStream();}catch(UnsupportedEncodingException e){e.printStackTrace();}catch(MalformedURLException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}return is;}public static void main(String args[]){String url = "https:///common/postcode/getPostCo deByAddr";String requestMethod = "POST";Map<String, String> params = new HashMap<String, String>(); params.put("apiKey","your_api_key"); //需要从获取params.put("page", ""); //页码(默认为1)params.put("pageSize", ""); //每页题目数量(默认为30)params.put("licenseType", ""); //驾照类型,0:小车(C1、C2),1:客车(A1、A3、B1),2:货车(A2、B2),3:摩托车(D、E、F)params.put("subjectType", ""); //科目类型,0:科目一,1:科目四(文明考试)String result = null;try{InputStream is = httpRequestToStream(url, requestMethod, pa rams);byte[] b = new byte[is.available()];is.read(b);result = new String(b);}catch(IOException e){e.printStackTrace();}if (result != null){JSONObject jsonObject = JSONObject.parseObject(result);String status_code = jsonObject.getString("statusCode");if (status_code == "000000"){// 状态码为000000, 说明请求成功System.out.println("请求成功:" + jsonObject.getString("resu lt"));}else{// 状态码非000000, 说明请求失败System.out.println("请求失败:" + jsonObject.getString("desc "));}}else{// 返回内容异常,发送请求失败,以下可根据业务逻辑自行修改System.out.println("发送请求失败");}}}3.关键字获取题目package net.apishop.www.controller;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLEncoder;import java.util.HashMap;import java.util.Map;import com.alibaba.fastjson.JSONObject;/*** httpUrlConnection访问远程接口工具*/public class Api{/*** 方法体说明:向远程接口发起请求,返回字节流类型结果* param url 接口地址* param requestMethod 请求方式* param params 传递参数重点:参数值需要用Base64进行转码* return InputStream 返回结果*/public static InputStream httpRequestToStream(String url, String re questMethod, Map<String, String> params){InputStream is = null;try{String parameters = "";boolean hasParams = false;// 将参数集合拼接成特定格式,如name=zhangsan&age=24for (String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");parameters += key + "=" + value + "&";hasParams = true;}if (hasParams){parameters = parameters.substring(0, parameters.length() - 1);}// 请求方式是否为getboolean isGet = "get".equalsIgnoreCase(requestMethod);// 请求方式是否为postboolean isPost = "post".equalsIgnoreCase(requestMethod);if (isGet){url += "?" + parameters;}URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnecti on();// 请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Con tent-Type为“”空)conn.setRequestProperty("Content-Type", "application/octet-stream");// conn.setRequestProperty("Content-Type", "application/x-w ww-form-urlencoded");// 设置连接超时时间conn.setConnectTimeout(50000);// 设置读取返回内容超时时间conn.setReadTimeout(50000);// 设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认falseif (isPost){conn.setDoOutput(true);}// 设置从HttpURLConnection对象读入,默认为trueconn.setDoInput(true);// 设置是否使用缓存,post方式不能使用缓存if (isPost){conn.setUseCaches(false);}// 设置请求方式,默认为GETconn.setRequestMethod(requestMethod);// post方式需要将传递的参数输出到conn对象中if (isPost){DataOutputStream dos = new DataOutputStream(conn.getOut putStream());dos.writeBytes(parameters);dos.flush();dos.close();}// 从HttpURLConnection对象中读取响应的消息// 执行该语句时才正式发起请求is = conn.getInputStream();}catch(UnsupportedEncodingException e){e.printStackTrace();}catch(MalformedURLException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}return is;}public static void main(String args[]){String url = "https:///common/postcode/getPostCo deByAddr";String requestMethod = "POST";Map<String, String> params = new HashMap<String, String>(); params.put("apiKey","your_api_key"); //需要从获取params.put("page", ""); //页码(默认为1)params.put("pageSize", ""); //每页题目数量(默认为30)params.put("licenseType", ""); //驾照类型,0:小车(C1、C2),1:客车(A1、A3、B1),2:货车(A2、B2),3:摩托车(D、E、F)params.put("subjectType", ""); //科目类型,0:科目一,1:科目四(文明考试)params.put("keyword", ""); //搜索关键字String result = null;try{InputStream is = httpRequestToStream(url, requestMethod, pa rams);byte[] b = new byte[is.available()];is.read(b);result = new String(b);}catch(IOException e){e.printStackTrace();}if (result != null){JSONObject jsonObject = JSONObject.parseObject(result);String status_code = jsonObject.getString("statusCode");if (status_code == "000000"){// 状态码为000000, 说明请求成功System.out.println("请求成功:" + jsonObject.getString("resu lt"));}else{// 状态码非000000, 说明请求失败System.out.println("请求失败:" + jsonObject.getString("desc "));}}else{// 返回内容异常,发送请求失败,以下可根据业务逻辑自行修改System.out.println("发送请求失败");}}}。

eoLinker-API_Shop_淘宝热词查询_API接口_Python调用示例代码

eoLinker-API_Shop_淘宝热词查询_API接口_Python调用示例代码

eoLinker-API Shop 淘宝热词查询 Python调用示例代码淘宝热词查询根据用户输入的关键词,实时查询该词在全站的搜索排名,协助商家全面掌控搜索关键词近期的市场排名,分布特征等。

该产品拥有以下APIs:1.淘宝热搜查询注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=212申请API服务1.淘宝热搜查询#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///common/shopping/queryTBRelatedHotWords" headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"keyword":"" #查询关键字}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')。

eoLinker-API_Shop_手机号归属地查询_API接口_Python调用示例代码

eoLinker-API_Shop_手机号归属地查询_API接口_Python调用示例代码

eoLinker-API Shop 手机号归属地查询 Python调用示例代码手机号归属地查询根据中国大陆手机号获取归属地信息。

该产品拥有以下APIs:1.根据手机号获取归属地信息注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=72申请API服务1.根据手机号获取归属地信息#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///communication/phone/getLocationByPhoneNu m"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"phoneNum":"" #目标手机号或手机号前7位}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')。

eoLinker-API_Shop_股票行情数据_API接口_Python调用示例代码

eoLinker-API_Shop_股票行情数据_API接口_Python调用示例代码

eoLinker-API Shop 股票行情数据 Python调用示例代码股票行情数据支持证券全市场行情数据,实时数据,K线数据,分笔数据,市场股票代码信息,历史数据等等,满足证券投资分析使用。

该产品拥有以下APIs:1.股票k线2.实时行情查询3.查询股票列表4.查询股票市场5.分笔6.分时查询7.指数实时报价8.组合行情查询9.综合排名注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=168申请API服务1.股票k线#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/kline"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码"period":"" #1:1分钟 2:5分钟 3:15分钟 4:30分钟 5:60分钟 6:日k 线 7:周k线 8:月k线"request_num":"" #请求行数"position_str":"" #定位串,默认-1 从头开始}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')2.实时行情查询#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/realtime"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')3.查询股票列表#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/list"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_type":"" #市场类别"request_num":"" #定位串,传空默认为20"position_str":"" #起始位空,从应答中获取}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')4.查询股票市场#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers) elif method == 'GET':return requests.get(url=url, params=params, headers=headers) else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/market"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')5.分笔#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/tick"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码"request_num":"" #请求参数}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')6.分时查询#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/trend"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')7.指数实时报价#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/index"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #代码}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')8.组合行情查询#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/comb"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')9.综合排名#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers) elif method == 'GET':return requests.get(url=url, params=params, headers=headers) else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/sort"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_type":"" #股票类别,参考市场查询返回值"sort_type":"" #排序类别}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')。

eoLinker-API_Shop_区块链今日快讯_API接口_C#调用示例代码

eoLinker-API_Shop_区块链今日快讯_API接口_C#调用示例代码

eoLinker-API Shop 区块链今日快讯 C#调用示例代码区块链今日快讯包括比特币、以太坊等热门区块链信息以及最新的相关资讯,实时更新。

该产品拥有以下APIs:1.获取区块链快讯列表2.搜索区块链快讯注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=185申请API服务1.获取区块链快讯列表using System;using System.Collections.Generic;using System.IO;using ;using System.Text;using System.Web.Script.Serialization;namespace apishop_sdk{class Program{/*** 转发请求到目的主机* @param method string 请求方法* @param url string 请求地址* @param params Dictionary<string,string> 请求参数* @param headers Dictionary<string,string> 请求头* @return string**/static string apishop_send_request(string method, string url, D ictionary<string, string> param, Dictionary<string, string> headers){string result = string.Empty;try{string paramData = "";if (param != null && param.Count > 0){StringBuilder sbuilder = new StringBuilder();foreach (var item in param){if (sbuilder.Length > 0){sbuilder.Append("&");}sbuilder.Append(item.Key + "=" + item.Value);}paramData = sbuilder.ToString();}method = method.ToUpper();if (method == "GET"){url = string.Format("{0}?{1}", url, paramData);}HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.C reate(url);if (method == "GET"){wbRequest.Method = "GET";}else if (method == "POST"){wbRequest.Method = "POST";wbRequest.ContentType = "application/x-www-form-url encoded";wbRequest.ContentLength = Encoding.UTF8.GetByteCoun t(paramData);using (Stream requestStream = wbRequest.GetRequestS tream()){using (StreamWriter swrite = new StreamWriter(r equestStream)){swrite.Write(paramData);}}}HttpWebResponse wbResponse = (HttpWebResponse)wbRequest. GetResponse();using (Stream responseStream = wbResponse.GetResponseSt ream()){using (StreamReader sread = new StreamReader(respon seStream)){result = sread.ReadToEnd();}}}catch{return "";}return result;}class Response{public string statusCode;}static void Main(string[] args){string method = "POST";string url = "https:///common/coin/getNewsLi st";Dictionary<string, string> param = new Dictionary<string, s tring>();param.Add("apiKey", "your_api_key"); //需要从www.apishop.ne t获取param.Add("page", ""); //页码(默认为1)param.Add("pageSize", ""); //每页条数(范围[10,40],默认每页1 0条)Dictionary<string, string> headers = null;string result = apishop_send_request(method, url, param, he aders);if (result == ""){//返回内容异常,发送请求失败Console.WriteLine("发送请求失败");return;}Response res = new JavaScriptSerializer().Deserialize<Respo nse>(result);if (res.statusCode == "000000"){//状态码为000000, 说明请求成功Console.WriteLine(string.Format("请求成功: {0}", resul t));}else{//状态码非000000, 说明请求失败Console.WriteLine(string.Format("请求失败: {0}", resul t));}Console.ReadLine();}}}2.搜索区块链快讯using System;using System.Collections.Generic;using System.IO;using ;using System.Text;using System.Web.Script.Serialization;namespace apishop_sdk{class Program{/*** 转发请求到目的主机* @param method string 请求方法* @param url string 请求地址* @param params Dictionary<string,string> 请求参数* @param headers Dictionary<string,string> 请求头* @return string**/static string apishop_send_request(string method, string url, D ictionary<string, string> param, Dictionary<string, string> headers){string result = string.Empty;try{string paramData = "";if (param != null && param.Count > 0){StringBuilder sbuilder = new StringBuilder();foreach (var item in param){if (sbuilder.Length > 0){sbuilder.Append("&");}sbuilder.Append(item.Key + "=" + item.Value); }paramData = sbuilder.ToString();}method = method.ToUpper();if (method == "GET"){url = string.Format("{0}?{1}", url, paramData);}HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.C reate(url);if (method == "GET"){wbRequest.Method = "GET";}else if (method == "POST"){wbRequest.Method = "POST";wbRequest.ContentType = "application/x-www-form-url encoded";wbRequest.ContentLength = Encoding.UTF8.GetByteCoun t(paramData);using (Stream requestStream = wbRequest.GetRequestS tream()){using (StreamWriter swrite = new StreamWriter(r equestStream)){swrite.Write(paramData);}}}HttpWebResponse wbResponse = (HttpWebResponse)wbRequest. GetResponse();using (Stream responseStream = wbResponse.GetResponseSt ream()){using (StreamReader sread = new StreamReader(respon seStream)){result = sread.ReadToEnd();}}}catch{return "";}return result;}class Response{public string statusCode;}static void Main(string[] args){string method = "POST";string url = "https:///common/coin/searchNew s";Dictionary<string, string> param = new Dictionary<string, s tring>();param.Add("apiKey", "your_api_key"); //需要从www.apishop.ne t获取param.Add("keyword", ""); //搜索关键字param.Add("page", ""); //页码(默认为1)param.Add("pageSize", ""); //每页条数(范围[10,40],默认每页1 0条)Dictionary<string, string> headers = null;string result = apishop_send_request(method, url, param, he aders);if (result == ""){//返回内容异常,发送请求失败Console.WriteLine("发送请求失败");return;}Response res = new JavaScriptSerializer().Deserialize<Respo nse>(result);if (res.statusCode == "000000"){//状态码为000000, 说明请求成功Console.WriteLine(string.Format("请求成功: {0}", resul t));}else{//状态码非000000, 说明请求失败Console.WriteLine(string.Format("请求失败: {0}", resul t));}Console.ReadLine();}}}。

eoLinker-API_Shop_猫咪大全_API接口_Python调用示例代码

eoLinker-API_Shop_猫咪大全_API接口_Python调用示例代码

eoLinker-API Shop 猫咪大全 Python调用示例代码猫咪大全可查询猫咪相关信息,包括品种介绍、产地、性格、寿命、价格等信息,带图片。

该产品拥有以下APIs:1.关键字获取猫类2.获取猫类列表3.获取猫类详细信息注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=193申请API服务1.关键字获取猫类#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///common/catFamily/queryCatListByKeyword" headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"page":"" #页码(默认为1)"pageSize":"" #当前页面猫咪数目(默认为30)"keyword":"" #关键字}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')2.获取猫类列表#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///common/catFamily/queryCatList"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"page":"" #页码(默认为1)"pageSize":"" #当前页面猫咪数目(默认为30)}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')3.获取猫类详细信息#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///common/catFamily/queryCatInfo"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"petID":"" #猫猫ID}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')。

eoLinker-API_Shop_POI检索_API接口_Java调用示例代码

eoLinker-API_Shop_POI检索_API接口_Java调用示例代码

eoLinker-API Shop POI检索 Java调用示例代码POI检索通过关键词查询在某个地区的POI信息,支持市级、区县级查询:比如在广州查询“银行”,接口将会输出所有银行的地理信息列表。

该产品拥有以下APIs:1.POI搜索2.周边POI搜索3.POI多边形搜索注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=97申请API服务1.POI搜索package net.apishop.www.controller;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLEncoder;import java.util.HashMap;import java.util.Map;import com.alibaba.fastjson.JSONObject;/*** httpUrlConnection访问远程接口工具*/public class Api{/*** 方法体说明:向远程接口发起请求,返回字节流类型结果* param url 接口地址* param requestMethod 请求方式* param params 传递参数重点:参数值需要用Base64进行转码* return InputStream 返回结果*/public static InputStream httpRequestToStream(String url, String requestMethod, Map<String, String> params){InputStream is = null;try{String parameters = "";boolean hasParams = false;// 将参数集合拼接成特定格式,如name=zhangsan&age=24for (String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");parameters += key + "=" + value + "&";hasParams = true;}if (hasParams){parameters = parameters.substring(0, parameters.length() - 1);}// 请求方式是否为getboolean isGet = "get".equalsIgnoreCase(requestMethod);// 请求方式是否为postboolean isPost = "post".equalsIgnoreCase(requestMethod);if (isGet){url += "?" + parameters;}URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnecti on();// 请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Con tent-Type为“”空)conn.setRequestProperty("Content-Type", "application/octet-stream");// conn.setRequestProperty("Content-Type", "application/x-w ww-form-urlencoded");// 设置连接超时时间conn.setConnectTimeout(50000);// 设置读取返回内容超时时间conn.setReadTimeout(50000);// 设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认falseif (isPost){conn.setDoOutput(true);}// 设置从HttpURLConnection对象读入,默认为trueconn.setDoInput(true);// 设置是否使用缓存,post方式不能使用缓存if (isPost){conn.setUseCaches(false);}// 设置请求方式,默认为GETconn.setRequestMethod(requestMethod);// post方式需要将传递的参数输出到conn对象中if (isPost){DataOutputStream dos = new DataOutputStream(conn.getOut putStream());dos.writeBytes(parameters);dos.flush();dos.close();}// 从HttpURLConnection对象中读取响应的消息// 执行该语句时才正式发起请求is = conn.getInputStream();}catch(UnsupportedEncodingException e){e.printStackTrace();}catch(MalformedURLException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}return is;}public static void main(String args[]){String url = "https:///common/postcode/getPostCo deByAddr";String requestMethod = "POST";Map<String, String> params = new HashMap<String, String>(); params.put("keyWords", ""); //查询关键字(规则:多个关键字用“|”分割若不指定city,并且搜索的为泛词(例如“美食”)的情况下,返回的内容为城市列表以及此城市内有多少结果符合要求。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

eoLinker-API Shop 猫咪大全 Java调用示例代码猫咪大全可查询猫咪相关信息,包括品种介绍、产地、性格、寿命、价格等信息,带图片。

该产品拥有以下APIs:1.关键字获取猫类2.获取猫类列表3.获取猫类详细信息注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=193申请API服务1.关键字获取猫类package net.apishop.www.controller;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLEncoder;import java.util.HashMap;import java.util.Map;import com.alibaba.fastjson.JSONObject;/*** httpUrlConnection访问远程接口工具*/public class Api{/*** 方法体说明:向远程接口发起请求,返回字节流类型结果* param url 接口地址* param requestMethod 请求方式* param params 传递参数重点:参数值需要用Base64进行转码* return InputStream 返回结果*/public static InputStream httpRequestToStream(String url, String re questMethod, Map<String, String> params){InputStream is = null;try{String parameters = "";boolean hasParams = false;// 将参数集合拼接成特定格式,如name=zhangsan&age=24for (String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");parameters += key + "=" + value + "&";hasParams = true;}if (hasParams){parameters = parameters.substring(0, parameters.length() - 1);}// 请求方式是否为getboolean isGet = "get".equalsIgnoreCase(requestMethod);// 请求方式是否为postboolean isPost = "post".equalsIgnoreCase(requestMethod);if (isGet){url += "?" + parameters;}URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnecti on();// 请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Con tent-Type为“”空)conn.setRequestProperty("Content-Type", "application/octet-stream");// conn.setRequestProperty("Content-Type", "application/x-w ww-form-urlencoded");// 设置连接超时时间conn.setConnectTimeout(50000);// 设置读取返回内容超时时间conn.setReadTimeout(50000);// 设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认falseif (isPost){conn.setDoOutput(true);}// 设置从HttpURLConnection对象读入,默认为trueconn.setDoInput(true);// 设置是否使用缓存,post方式不能使用缓存if (isPost){conn.setUseCaches(false);}// 设置请求方式,默认为GETconn.setRequestMethod(requestMethod);// post方式需要将传递的参数输出到conn对象中if (isPost){DataOutputStream dos = new DataOutputStream(conn.getOut putStream());dos.writeBytes(parameters);dos.flush();dos.close();}// 从HttpURLConnection对象中读取响应的消息// 执行该语句时才正式发起请求is = conn.getInputStream();}catch(UnsupportedEncodingException e){e.printStackTrace();}catch(MalformedURLException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}return is;}public static void main(String args[]){String url = "https:///common/postcode/getPostCo deByAddr";String requestMethod = "POST";Map<String, String> params = new HashMap<String, String>(); params.put("apiKey","your_api_key"); //需要从获取params.put("page", ""); //页码(默认为1)params.put("pageSize", ""); //当前页面猫咪数目(默认为30)params.put("keyword", ""); //关键字String result = null;try{InputStream is = httpRequestToStream(url, requestMethod, pa rams);byte[] b = new byte[is.available()];is.read(b);result = new String(b);}catch(IOException e){e.printStackTrace();}if (result != null){JSONObject jsonObject = JSONObject.parseObject(result);String status_code = jsonObject.getString("statusCode");if (status_code == "000000"){// 状态码为000000, 说明请求成功System.out.println("请求成功:" + jsonObject.getString("resu lt"));}else{// 状态码非000000, 说明请求失败System.out.println("请求失败:" + jsonObject.getString("desc "));}}else{// 返回内容异常,发送请求失败,以下可根据业务逻辑自行修改System.out.println("发送请求失败");}}}2.获取猫类列表package net.apishop.www.controller;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLEncoder;import java.util.HashMap;import java.util.Map;import com.alibaba.fastjson.JSONObject;/*** httpUrlConnection访问远程接口工具*/public class Api{/*** 方法体说明:向远程接口发起请求,返回字节流类型结果* param url 接口地址* param requestMethod 请求方式* param params 传递参数重点:参数值需要用Base64进行转码* return InputStream 返回结果*/public static InputStream httpRequestToStream(String url, String re questMethod, Map<String, String> params){InputStream is = null;try{String parameters = "";boolean hasParams = false;// 将参数集合拼接成特定格式,如name=zhangsan&age=24for (String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");parameters += key + "=" + value + "&";hasParams = true;}if (hasParams){parameters = parameters.substring(0, parameters.length() - 1);}// 请求方式是否为getboolean isGet = "get".equalsIgnoreCase(requestMethod);// 请求方式是否为postboolean isPost = "post".equalsIgnoreCase(requestMethod);if (isGet){url += "?" + parameters;}URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnecti on();// 请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Con tent-Type为“”空)conn.setRequestProperty("Content-Type", "application/octet-stream");// conn.setRequestProperty("Content-Type", "application/x-w ww-form-urlencoded");// 设置连接超时时间conn.setConnectTimeout(50000);// 设置读取返回内容超时时间conn.setReadTimeout(50000);// 设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认falseif (isPost){conn.setDoOutput(true);}// 设置从HttpURLConnection对象读入,默认为trueconn.setDoInput(true);// 设置是否使用缓存,post方式不能使用缓存if (isPost){conn.setUseCaches(false);}// 设置请求方式,默认为GETconn.setRequestMethod(requestMethod);// post方式需要将传递的参数输出到conn对象中if (isPost){DataOutputStream dos = new DataOutputStream(conn.getOut putStream());dos.writeBytes(parameters);dos.flush();dos.close();}// 从HttpURLConnection对象中读取响应的消息// 执行该语句时才正式发起请求is = conn.getInputStream();}catch(UnsupportedEncodingException e){e.printStackTrace();}catch(MalformedURLException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}return is;}public static void main(String args[]){String url = "https:///common/postcode/getPostCo deByAddr";String requestMethod = "POST";Map<String, String> params = new HashMap<String, String>(); params.put("apiKey","your_api_key"); //需要从获取params.put("page", ""); //页码(默认为1)params.put("pageSize", ""); //当前页面猫咪数目(默认为30)String result = null;try{InputStream is = httpRequestToStream(url, requestMethod, pa rams);byte[] b = new byte[is.available()];is.read(b);result = new String(b);}catch(IOException e){e.printStackTrace();}if (result != null){JSONObject jsonObject = JSONObject.parseObject(result);String status_code = jsonObject.getString("statusCode");if (status_code == "000000"){// 状态码为000000, 说明请求成功System.out.println("请求成功:" + jsonObject.getString("resu lt"));}else{// 状态码非000000, 说明请求失败System.out.println("请求失败:" + jsonObject.getString("desc "));}}else{// 返回内容异常,发送请求失败,以下可根据业务逻辑自行修改System.out.println("发送请求失败");}}}3.获取猫类详细信息package net.apishop.www.controller;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLEncoder;import java.util.HashMap;import java.util.Map;import com.alibaba.fastjson.JSONObject;/*** httpUrlConnection访问远程接口工具*/public class Api{/*** 方法体说明:向远程接口发起请求,返回字节流类型结果* param url 接口地址* param requestMethod 请求方式* param params 传递参数重点:参数值需要用Base64进行转码* return InputStream 返回结果*/public static InputStream httpRequestToStream(String url, String re questMethod, Map<String, String> params){InputStream is = null;try{String parameters = "";boolean hasParams = false;// 将参数集合拼接成特定格式,如name=zhangsan&age=24for (String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");parameters += key + "=" + value + "&";hasParams = true;}if (hasParams){parameters = parameters.substring(0, parameters.length() - 1);}// 请求方式是否为getboolean isGet = "get".equalsIgnoreCase(requestMethod);// 请求方式是否为postboolean isPost = "post".equalsIgnoreCase(requestMethod);if (isGet){url += "?" + parameters;}URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnecti on();// 请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Con tent-Type为“”空)conn.setRequestProperty("Content-Type", "application/octet-stream");// conn.setRequestProperty("Content-Type", "application/x-w ww-form-urlencoded");// 设置连接超时时间conn.setConnectTimeout(50000);// 设置读取返回内容超时时间conn.setReadTimeout(50000);// 设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认falseif (isPost){conn.setDoOutput(true);}// 设置从HttpURLConnection对象读入,默认为trueconn.setDoInput(true);// 设置是否使用缓存,post方式不能使用缓存if (isPost){conn.setUseCaches(false);}// 设置请求方式,默认为GETconn.setRequestMethod(requestMethod);// post方式需要将传递的参数输出到conn对象中if (isPost){DataOutputStream dos = new DataOutputStream(conn.getOut putStream());dos.writeBytes(parameters);dos.flush();dos.close();}// 从HttpURLConnection对象中读取响应的消息// 执行该语句时才正式发起请求is = conn.getInputStream();}catch(UnsupportedEncodingException e){e.printStackTrace();}catch(MalformedURLException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}return is;}public static void main(String args[]){String url = "https:///common/postcode/getPostCo deByAddr";String requestMethod = "POST";Map<String, String> params = new HashMap<String, String>(); params.put("apiKey","your_api_key"); //需要从获取params.put("petID", ""); //猫猫IDString result = null;try{InputStream is = httpRequestToStream(url, requestMethod, pa rams);byte[] b = new byte[is.available()];is.read(b);result = new String(b);}catch(IOException e){e.printStackTrace();}if (result != null){JSONObject jsonObject = JSONObject.parseObject(result);String status_code = jsonObject.getString("statusCode");if (status_code == "000000"){// 状态码为000000, 说明请求成功System.out.println("请求成功:" + jsonObject.getString("resu lt"));}else{// 状态码非000000, 说明请求失败System.out.println("请求失败:" + jsonObject.getString("desc "));}}else{// 返回内容异常,发送请求失败,以下可根据业务逻辑自行修改System.out.println("发送请求失败");}}}。

相关文档
最新文档