gpt4 book ai didi

java - HttpPost 转义参数

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:28 26 4
gpt4 key购买 nike

我正在尝试使用 HttpClient(HttpComponents) 制作 HttpPost。这是我的代码:

try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://accounts.google.com/o/oauth2/token");
post.addHeader("accept", "application/json");
post.addHeader("Content-Type", "application/json");

List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("code", new String(code.getBytes(), Charset.forName("UTF-8"))));
nvps.add(new BasicNameValuePair("client_id", "googleClientId"));
nvps.add(new BasicNameValuePair("redirect_uri", "http://localhost:8080/myapp/test"));
nvps.add(new BasicNameValuePair("client_secret", "ClientSecret"));
nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));


HttpResponse resp = httpClient.execute(post);

if (resp.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ resp.getStatusLine().getStatusCode());
}

BufferedReader br = new BufferedReader(
new InputStreamReader((resp.getEntity().getContent())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
res = res + output;
}
System.out.println(output);
httpClient.getConnectionManager().shutdown();
} catch(Exception e){
e.printStackTrace();
}
System.out.println(res);

我收到 400 代码。我怀疑这是因为我设置的所有参数都包含特殊字符,例如 _ 。和/ 他们正在逃脱。我怎样才能避免这种情况?或者我错过了真正的问题?

最佳答案

既然您对 post 参数进行了显式 URL 编码,那么 http header “Content-Type”不应​​该是 application/x-www-form-urlencoded 吗?

关于java - HttpPost 转义参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com