(.NET)怎么调用淘宝API,获取个人信息.并显示出来.俺是菜鸟,请关照.QQ:769421543
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(.NET)怎么调用淘宝API,获取个人信息.并显示出来.俺是菜鸟,请关照.QQ:769421543相关的知识,希望对你有一定的参考价值。
其实淘宝会提供的api 调用的例子你找找就有的在淘宝网上--- TaoBaoAPI.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;
using System.Net;
using System.IO;
using ESCM.Base.SQLOperation;
using ESCM.Base.EntityDAO;
using System.Security.Cryptography;
namespace ESCM.Base
public static class TaoBaoAPI
/// <summary>
/// 执行淘宝API
/// </summary>
/// <param name="paraList">参数列表</param>
/// <param name="keyStr">密钥</param>
/// <param name="apiUseType">使用类型</param>
/// <returns></returns>
public static TaoBaoApiRequestResuleType execute(SortedList paraList, string keyStr, TaoBaoApiUsageType taoBaoApiUsageType, Decimal userGUID, string xmlFileName)
Signature.Code = keyStr;
string sipSign = Signature.DoSignature(paraList);
string sipDate = "";
foreach (DictionaryEntry entry in paraList)
sipDate = sipDate + "&" + entry.Key + "=" + entry.Value;
//必须将sign 放在 字符串的最后
sipDate = sipDate.Substring(1, sipDate.Length - 1) + "&sign=" + sipSign;
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] postData = encoding.GetBytes(sipDate);//所有要传参数拼装
try
//发送
HttpWebRequest httpWebRequest = null;
httpWebRequest = (HttpWebRequest)WebRequest.Create("");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = postData.Length;
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(postData, 0, postData.Length);
stream.Close();
//接收
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
HttpStatusCode StatusCode = httpWebResponse.StatusCode;
if (StatusCode == HttpStatusCode.OK)
StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
string content = reader.ReadToEnd();
if (content == "")
return TaoBaoApiRequestResuleType.DataNull;
else
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(content);
if (xmlDoc.DocumentElement.Name == "error_rsp")
XmlNode node = xmlDoc.SelectSingleNode("error_rsp/msg");
return TaoBaoApiRequestResuleType.ParaErr;
else
switch (taoBaoApiUsageType)
case TaoBaoApiUsageType.SingleItem:
try
return TaoBaoApiRequestResuleType.RequestSucess;
catch (Exception Ex)
return TaoBaoApiRequestResuleType.SaveErr;
case TaoBaoApiUsageType.MutiItem:
try
xmlDoc.Save(xmlFileName);
return TaoBaoApiRequestResuleType.RequestSucess;
catch (Exception Ex)
return TaoBaoApiRequestResuleType.SaveErr;
case TaoBaoApiUsageType.SingleOrder:
try
return TaoBaoApiRequestResuleType.RequestSucess;
catch (Exception Ex)
return TaoBaoApiRequestResuleType.SaveErr;
case TaoBaoApiUsageType.MutiOrder:
try
xmlDoc.Save(xmlFileName);
return TaoBaoApiRequestResuleType.RequestSucess;
catch (Exception Ex)
return TaoBaoApiRequestResuleType.SaveErr;
case TaoBaoApiUsageType.SingleCustomer:
try
return TaoBaoApiRequestResuleType.RequestSucess;
catch (Exception Ex)
return TaoBaoApiRequestResuleType.SaveErr;
default:
return TaoBaoApiRequestResuleType.InValideAPI;
break;
else
return TaoBaoApiRequestResuleType.RequestFaile;
catch (Exception ex)
return TaoBaoApiRequestResuleType.exceptionErr;
/// <summary>
/// 执行HTTP POST请求。
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="parameters">请求参数</param>
/// <returns>HTTP响应</returns>
public static string DoPost(IDictionary<string, string> parameters)
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("");
req.Method = "POST";
req.KeepAlive = true;
req.ContentType = "application/x-www-form-urlencoded";
byte[] postData = Encoding.UTF8.GetBytes(BuildPostData(parameters));
Stream reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
/// <summary>
/// 执行HTTP GET请求。
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="parameters">请求参数</param>
/// <returns>HTTP响应</returns>
public static string DoGet(string url, IDictionary<string, string> parameters)
if (parameters != null && parameters.Count > 0)
if (url.Contains("?"))
url = url + "&" + BuildPostData(parameters);
else
url = url + "?" + BuildPostData(parameters);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.KeepAlive = true;
req.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
/// <summary>
/// 执行带文件上传的HTTP POST请求。
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="textParams">请求文本参数</param>
/// <param name="fileParams">请求文件参数</param>
/// <returns>HTTP响应</returns>
public static string DoPost(IDictionary<string, string> textParams, IDictionary<string, FileInfo> fileParams)
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("");
req.Method = "POST";
req.KeepAlive = true;
req.ContentType = "multipart/form-data;boundary=" + boundary;
Stream reqStream = req.GetRequestStream();
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
// 组装文本请求参数
string entryTemplate = "Content-Disposition:form-data;name=\"\"\r\nContent-Type:text/plain\r\n\r\n";
IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
while (textEnum.MoveNext())
string formItem = string.Format(entryTemplate, textEnum.Current.Key, textEnum.Current.Value);
byte[] itemBytes = Encoding.UTF8.GetBytes(formItem);
reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
reqStream.Write(itemBytes, 0, itemBytes.Length);
// 组装文件请求参数
string fileTemplate = "Content-Disposition:form-data;name=\"\";filename=\"\"\r\nContent-Type:\r\n\r\n";
IEnumerator<KeyValuePair<string, FileInfo>> fileEnum = fileParams.GetEnumerator();
while (fileEnum.MoveNext())
string key = fileEnum.Current.Key;
FileInfo file = fileEnum.Current.Value;
string fileItem = string.Format(fileTemplate, key, file.FullName, GetMimeType(file.FullName));
byte[] itemBytes = Encoding.UTF8.GetBytes(fileItem);
reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
reqStream.Write(itemBytes, 0, itemBytes.Length);
using (Stream fileStream = file.OpenRead())
byte[] buffer = new byte[1024];
int readBytes = 0;
while ((readBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)
reqStream.Write(buffer, 0, readBytes);
reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
reqStream.Close();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
/// <summary>
/// 把响应流转换为文本。
/// </summary>
/// <param name="rsp">响应流对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>响应文本</returns>
private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
StringBuilder result = new StringBuilder();
Stream stream = null;
StreamReader reader = null;
try
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
// 每次读取不大于512个字符,并写入字符串
char[] buffer = new char[512];
int readBytes = 0;
while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
result.Append(buffer, 0, readBytes);
finally
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
return result.ToString();
/// <summary>
/// 根据文件名后缀获取图片型文件的Mime-Type。
/// </summary>
/// <param name="filePath">文件全名</param>
/// <returns>图片文件的Mime-Type</returns>
private static string GetMimeType(string filePath)
string mimeType;
switch (Path.GetExtension(filePath).ToLower())
case ".bmp": mimeType = "image/bmp"; break;
case ".gif": mimeType = "image/gif"; break;
case ".ico": mimeType = "image/x-icon"; break;
case ".jpeg": mimeType = "image/jpeg"; break;
case ".jpg": mimeType = "image/jpeg"; break;
case ".png": mimeType = "image/png"; break;
default: mimeType = "application/octet-stream"; break;
return mimeType;
/// <summary>
/// 组装普通文本请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
private static string BuildPostData(IDictionary<string, string> parameters)
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
if (hasParam)
postData.Append("&");
postData.Append(name);
postData.Append("=");
postData.Append(Uri.EscapeDataString(value));
hasParam = true;
return postData.ToString();
/// <summary>
/// 给TOP请求签名。
/// </summary>
/// <param name="parameters">所有字符型的TOP请求参数</param>
/// <param name="secret">签名密钥</param>
/// <returns>签名</returns>
public static string SignTopRequest(IDictionary<string, string> parameters, string secret)
// 第一步:把字典按Key的字母顺序排序
IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
// 第二步:把所有参数名和参数值串在一起
StringBuilder query = new StringBuilder(secret);
while (dem.MoveNext())
string key = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
query.Append(key).Append(value);
// 第三步:使用MD5加密
MD5 md5 = MD5.Create();
byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
// 第四步:把二进制转化为大写的十六进制
StringBuilder result = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
string hex = bytes[i].ToString("X");
if (hex.Length == 1)
result.Append("0");
result.Append(hex);
return result.ToString();
/// <summary>
/// 清除字典中值为空的项。
/// </summary>
/// <param name="dict">待清除的字典</param>
/// <returns>清除后的字典</returns>
public static IDictionary<string, string> CleanupDictionary(IDictionary<string, string> dict)
IDictionary<string, string> newDict = new Dictionary<string, string>();
IEnumerator<KeyValuePair<string, string>> dem = dict.GetEnumerator();
while (dem.MoveNext())
string name = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(value))
newDict.Add(name, value);
return newDict;
参考技术A 不是谁想调用就可以调用的.
第一,你需要这些信息,就要去和淘宝谈,要合法的信息使用和注意信息保密.
第二,和淘宝达成协议后,一般会以web服务的形式提供给你这些信息.
第三,在你的系统中调用服务来获取这些信息.
调用手机在线API获取手机号码归属地信息
手机在线(www.showji.com)始创于2001年,发展至今已拥有国内最准确、号段容量最大的手机号码归属地数据库系统,
目前号段容量将近33万条,每月保持两次以上规模数据更新,合作伙伴包括:百度、淘宝、腾讯、搜狗、小米手机、宝马汽车、
神马搜索、点心OS等。
手机在线号码归属地提供WebService、HTTP API、免费调用和付费数据库四种使用方式:
可以通过URL GET超链接的方式来获取手机号归属地信息,每IP每分钟调用20次的限制,具体实现如下:
import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 通过手机号码,获得该号码的归属地、运营商等信息 */ public class ShoujiHelper { public static final String SHOUJI_URL = "http://v.showji.com/Locating/showji.com2016234999234.aspx"; public static final String REGEX_IS_MOBILE ="(?is)(^1[3|4|5|7|8][0-9]\\d{4,8}$)";// 正则表达式,可以只输入手机号码前7位 /** * 根据手机号码获取归属地信息 * @param mobileNumber * @throws Exception */ public static String getMobileFrom(String mobileNumber) throws Exception { if (!veriyMobile(mobileNumber)) { throw new Exception("不是完整的11位手机号或者正确的手机号前七位"); } String URL = SHOUJI_URL+"?m="+mobileNumber+"&output=json&callback=querycallback×tamp="+System.currentTimeMillis(); String result = HttpUtil.readContentFromGet(URL); if( result != null ){ result = StringUtils.substringBetween(result, "(", ")"); } return result; } /** *验证手机号格式 是否符合 *@param mobileNumber */ public static boolean veriyMobile(String mobileNumber) { Pattern p = Pattern.compile(REGEX_IS_MOBILE); Matcher m = p.matcher(mobileNumber); return m.matches(); } //测试一下 public static void main(String[] args) throws Exception { long[] phones={ 18190282387L,18081685555L,18013715591L,18092163043L,18370631995L, 18026799125L,18056538590L,18038692012L,18083766020L,18092015835L, 18060923366L,18078158869L,18041153288L,18028690873L,18028796251L, 13585859733L,15961230678L,18937295656L,18056649455L,15640694239L, 18958283918L,18966551516L,15353951523L,18025114334L,15071469692L, 15139914717L,13738618263L,13181207626L,13516035175L,15327038012L, 18659138399L,15151920785L,18969515188L,13064025146L,15619969722L }; int successNum = 0, dealNum = 20; for(int i=0; i < dealNum; i++){ String result = getMobileFrom(phones[i]+""); System.out.println(result); if (result!=null && result.contains("True")) { successNum++; } } System.out.println("========================="); System.out.println("| 处理的号码总数=="+dealNum); System.out.println("| 获取成功的个数=="+successNum); System.out.println("| 获取失败的个数=="+(dealNum-successNum)); System.out.println("========================="); } }
通过GET_URL调用接口获取内容的工具类HttpUtil
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.apache.commons.io.IOUtils; public class HttpUtil { /** * 通过GET_URL调用接口获取内容 */ public static String readContentFromGet(String GET_URL) throws IOException { String result = null; BufferedReader reader = null; HttpURLConnection connection = null; try{ String getURL = GET_URL; URL getUrl = new URL(getURL); // 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型, connection = (HttpURLConnection) getUrl.openConnection(); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("contentType", "UTF-8"); connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); // 进行连接 connection.connect(); // 取得输入流,并使用Reader读取 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); String line = null; StringBuffer lines = new StringBuffer(); while ((line = reader.readLine()) != null) { lines.append(line); } result = lines.toString(); } catch (Exception e) { System.out.println("GET_URL Result Exception : "+e.getMessage()); } finally { // 释放资源 断开连接 IOUtils.closeQuietly(reader); connection.disconnect(); connection = null; } return result; } }
每IP每分钟调用20次输出结果:
{"Mobile":"18190282387","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"四川","City":"资阳","AreaCode":"0832","PostCode":"641300","VNO":"","Card":""} {"Mobile":"18081685555","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"四川","City":"资阳","AreaCode":"0832","PostCode":"641300","VNO":"","Card":""} {"Mobile":"18013715591","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"江苏","City":"苏州","AreaCode":"0512","PostCode":"215000","VNO":"","Card":""} {"Mobile":"18092163043","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"陕西","City":"西安","AreaCode":"029","PostCode":"710000","VNO":"","Card":""} {"Mobile":"18370631995","QueryResult":"True","TO":"中国移动","Corp":"中国移动","Province":"江西","City":"吉安","AreaCode":"0796","PostCode":"343000","VNO":"","Card":""} {"Mobile":"18026799125","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"广东","City":"江门","AreaCode":"0750","PostCode":"529000","VNO":"","Card":""} {"Mobile":"18056538590","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"安徽","City":"芜湖","AreaCode":"0553","PostCode":"241000","VNO":"","Card":""} {"Mobile":"18038692012","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"广东","City":"佛山","AreaCode":"0757","PostCode":"528000","VNO":"","Card":""} {"Mobile":"18083766020","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"江苏","City":"扬州","AreaCode":"0514","PostCode":"225000","VNO":"","Card":""} {"Mobile":"18092015835","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"陕西","City":"西安","AreaCode":"029","PostCode":"710000","VNO":"","Card":""} {"Mobile":"18060923366","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"福建","City":"厦门","AreaCode":"0592","PostCode":"361000","VNO":"","Card":""} {"Mobile":"18078158869","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"广西","City":"南宁","AreaCode":"0771","PostCode":"530000","VNO":"","Card":""} {"Mobile":"18041153288","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"辽宁","City":"大连","AreaCode":"0411","PostCode":"116000","VNO":"","Card":""} {"Mobile":"18028690873","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"广东","City":"广州","AreaCode":"020","PostCode":"510000","VNO":"","Card":""} {"Mobile":"18028796251","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"广东","City":"深圳","AreaCode":"0755","PostCode":"518000","VNO":"","Card":""} {"Mobile":"13585859733","QueryResult":"True","TO":"中国移动","Corp":"中国移动","Province":"上海","City":"上海","AreaCode":"021","PostCode":"200000","VNO":"","Card":""} {"Mobile":"15961230678","QueryResult":"True","TO":"中国移动","Corp":"中国移动","Province":"江苏","City":"常州","AreaCode":"0519","PostCode":"213000","VNO":"","Card":""} {"Mobile":"18937295656","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"河南","City":"安阳","AreaCode":"0372","PostCode":"455000","VNO":"","Card":""} {"Mobile":"18056649455","QueryResult":"True","TO":"中国电信","Corp":"中国电信","Province":"安徽","City":"池州","AreaCode":"0566","PostCode":"247100","VNO":"","Card":""} {"Mobile":"15640694239","QueryResult":"True","TO":"中国联通","Corp":"中国联通","Province":"辽宁","City":"锦州","AreaCode":"0416","PostCode":"121000","VNO":"","Card":""} ========================= | 处理的号码总数==20 | 获取成功的个数==20 | 获取失败的个数==0 =========================
以上是关于(.NET)怎么调用淘宝API,获取个人信息.并显示出来.俺是菜鸟,请关照.QQ:769421543的主要内容,如果未能解决你的问题,请参考以下文章