这几天因为网站需求需要获取百度推广关键确定推广效果和推广转换率。
看了很多技术类的文章都不能实现获取百度推广关键词,通过对百度营销工具的研究终于成功。
现讲方法总结如下:
1、需要百度推广账户配合解决问题,在百度推广账户中带上keywordid,如下:https://www.baidu.com/?keywordid=228750344738&bd_vid=11103066373950979952
2、在网站上获取对应的keywordid,通过百度接口获取关键词。
接口地址为:https://api.baidu.com/json/sms/service/KeywordService/getWord
如何获取授权toke:打开如下地址,https://dev2.baidu.com/content?sceneType=1&pageId=100369&nodeId=16&subhead=,进入新手入门按照步骤开通。
Java代码示例:
package com.baidu.dev2.sdk;
import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response;
import java.io.IOException;
public class Dev2Example { public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); private OkHttpClient client = new OkHttpClient();
public static void main(String[] argcs) throws IOException { String json = "{"header":{"password":"百度推广密码","username":"百度推广账号","token":"百度权限toke","action":"API-JAVA"},"body":{"wordFields":["keywordId"],"ids":[228750344738],"idType":11,"getTemp":"0"}}"; String url = "https://api.baidu.com/json/sms/service/KeywordService/getWord";
Dev2Example dev2Example = new Dev2Example(); String result = dev2Example.post(url, json); System.out.println(result); }
private String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(json, JSON); Request request = new Request.Builder().url(url).post(body).build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } }
c#代码实例:
String json = "{"header":{"password":"Yy..123789","username":"SF神龙","token":"7fd1a1ca6b291ac7031a835eae98f6be","action":"API-JAVA"},"body":{"wordFields":["keywordId"],"ids":[228750344738],"idType":11,"getTemp":"0"}}"; String url = "https://api.baidu.com/json/sms/service/KeywordService/getWord";
string returnText = Tool.HttpHelper.PostUrl(url, json);
PostUrl方法:
public static string PostUrl(string url, string postData) { byte[] data = Encoding.UTF8.GetBytes(postData);
// 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; cookieContainer cookieContainer = new cookieContainer(); request.cookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; Stream outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close();
//发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream instream = response.GetResponseStream(); StreamReader sr = new StreamReader(instream, Encoding.UTF8); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; }
返回结果,包含关键词,自行解析json获取。