Java集成TikTok登录获取Access Token遇参数错误10002求助
解决TikTok登录获取Access Token的参数错误问题
问题根源
你遇到的error_code:10002错误,是因为将code、grant_type等必填参数放在了HTTP请求头中,而TikTok的access_token接口要求这些参数以表单数据(x-www-form-urlencoded)的形式放在请求体里,不是请求头。
Java环境下的正确实现代码
import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import java.util.ArrayList; import java.util.List; public class TikTokAccessTokenFetcher { public static void main(String[] args) throws Exception { String code = "你的授权code"; String clientKey = "你的client_key"; String clientSecret = "你的client_secret"; // 构造请求地址 HttpPost post = new HttpPost("https://open-api.tiktok.com/oauth/access_token/"); // 组装表单参数 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("code", code)); params.add(new BasicNameValuePair("grant_type", "authorization_code")); params.add(new BasicNameValuePair("client_key", clientKey)); params.add(new BasicNameValuePair("client_secret", clientSecret)); // 设置请求体为表单格式 post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // 必须设置Content-Type头 post.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 执行请求 try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpResponse httpResponse = httpclient.execute(post); // 后续处理响应逻辑,比如读取响应体 } } }
关键注意点
- 所有必填参数(code、grant_type、client_key、client_secret)都要放入
UrlEncodedFormEntity作为请求体,不要放在请求头 - 必须设置
Content-Type为application/x-www-form-urlencoded,确保服务端能正确解析参数 - 注意替换代码中的
code、client_key、client_secret为实际值
内容的提问来源于stack exchange,提问作者curious1
相关产品推荐
相关产品推荐

