gpt4 book ai didi

java - java HTTP post 中的 HTTP/1.1 400 错误请求

转载 作者:行者123 更新时间:2023-12-01 12:54:38 25 4
gpt4 key购买 nike

我正在尝试使用带有凭据的 HTTP post 方法将 xml 数据发布到 API,但出现 HTTP/1.1 400 Bad Request 错误..任何人都可以帮助我......

这是我的示例代码:

BufferedReader br = new BufferedReader(new FileReader(new File("Data.xml")));

StringBuilder sb = new StringBuilder();

while((line=br.readLine())!= null){
sb.append(line.trim());
}
System.out.println("xml: "+sb);



params=sb.toString();
HttpPost request = new HttpPost("*****************url***************");
String urlaparam=URLEncoder.encode("importFormatCode:1&data:"+params,"UTF-8");
String userCredentials = "****:******";
byte[] auth = Base64.encodeBase64(userCredentials.getBytes());

StringEntity entity=new StringEntity(urlaparam);
request.addHeader("Content-type","application/x-www-form-urlencoded");
request.addHeader("Accept", "application/xml");
request.addHeader("Accept-Language", "en-US,en;q=0.5");
request.addHeader("Authorization", "Basic " + new String(auth));


request.setEntity(entity);
HttpResponse response = httpClient.execute(request);

System.out.println(response.getStatusLine());
System.out.println(request);
}
catch(Exception e)
{
}

最佳答案

首先,您的表单参数编码不正确。您使用冒号 (:) 将键与其值分开,但必须使用等号 (=):

  • 错误:“importFormatCode:1&data:”+ params
  • 正确:"importFormatCode=1&data="+ params

(另请参阅 W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded )

除此之外,您不能对整个字符串进行 URL 编码,而只能对键和值进行 URL 编码。否则,您还将对分隔符 =&!

进行编码

最简单的方法是使用现有的实用程序类org.apache.http.client.utils.URLEncodedUtils(假设您使用的是 Apache HTTP Components ):

String xmlData = // your xml data from somewhere

List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("importFormatCode", "1"),
new BasicNameValuePair("data", xmlData)
);
String body = URLEncodedUtils.format(params, encoding); // use encoding of request

StringEntity entity = new StringEntity(body);
// rest of your code

关于java - java HTTP post 中的 HTTP/1.1 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23992356/

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