个人资料

主页 博客 留言板 搜索
跳过导航链接首页 > 博客列表 > 博客正文

c#使用百度翻译接口

分类

     定义baidu返回的json对应的类

namespace EasyNote.Translate.Baidu

{


public class Rootobject

{

public string from { get; set; }

public string to { get; set; }

public string domain { get; set; }

public int type { get; set; }

public int status { get; set; }

public Datum[] data { get; set; }

public int error { get; set; }

public string msg { get; set; }

}


public class Datum

{

public string dst { get; set; }

public int prefixWrap { get; set; }

public string src { get; set; }

public object[] relation { get; set; }

public object[][] result { get; set; }

}


}

    调用函数

public static async Task<EasyNote.Translate.Baidu.Rootobject> Baidu_Translate(string from, string to, string content)

{

EasyNote.Translate.Baidu.Rootobject result=null;

string TranslateUrl = $"http://fanyi.baidu.com/transapi?from={from}&to={to}&query={content}";

try

{

byte[] postData = System.Text.Encoding.UTF8.GetBytes(TranslateUrl);

// 设置提交的相关参数   

HttpWebRequest request = WebRequest.Create(TranslateUrl) as HttpWebRequest;

Encoding myEncoding = Encoding.UTF8;

request.Method = "POST";



request.ContentType = "text/plain";

//request.Headers


// 提交请求数据   

using (Stream InputStream = await request.GetRequestStreamAsync())

{

InputStream.Write(postData, 0, postData.Length);

}


using (WebResponse response = await request.GetResponseAsync())

{

Stream myResponseStream = response.GetResponseStream();

using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8))

{

string json = myStreamReader.ReadToEnd();

Debug.WriteLine(json);

result = JsonConvert.DeserializeObject<EasyNote.Translate.Baidu.Rootobject>(json);

}

}

}

catch (Exception ex)

{

Debug.WriteLine(ex.Message);

return null;

}


return result;



}


此接口为免费接口,随时失效.稳定的可以前往百度开发者中心配置AppID.

http://api.fanyi.baidu.com/api/trans/product/apidoc


admin
最初发表2019/1/19 23:01:52 最近更新2019/2/11 20:07:55 899
为此篇作品打分
10