gpt4 book ai didi

Java (Android),方法 POST,Web 格式而不是 JSON

转载 作者:行者123 更新时间:2023-12-01 09:06:24 34 4
gpt4 key购买 nike

我有代码

HttpHeaders headers = new HttpHeaders();
headers.set("Current-Version", "v1");

LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("email", "test@test.test");
HttpEntity<MultiValueMap<String, String>> request =
new HttpEntity<MultiValueMap<String, String>>(map, headers);

HttpEntity<Login> response = getRestTemplate().exchange(
url,
HttpMethod.POST,
request ,
Login.class
);

这很好用,但在服务器端,我得到了 JSON 格式的请求正文,尽管 Web 格式是 param1=val1&param2=val2。我必须以 param1=val1&param2=val2 格式向服务器发送 POST 请求。

我该怎么做?

最佳答案

只需使用下面的方法即可。

public static String getPostDataString(HashMap<Object, Object> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<Object, Object> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(entry.getKey().toString()));
result.append("=");
result.append(URLEncoder.encode(entry.getValue().toString()));
}

return result.toString();
}

使用

   try{  
String requestJSON = getPostDataString(inputData);
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}

将所有数据放入HashMap中,并在该方法中传递HashMap,您将获得param1=val1&param2=val2格式的请求字符串。

示例。

HashMap<Object, Object> map = new HashMap<>();
map.put("email", "test@test.test");
map.put("password", "testtest");
map.put("type", "1");

现在在方法中传递上面的HashMap

字符串requestString = "";

try{
requestString = getPostDataString(map);
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}

您将获得以下格式的请求字符串。

“email=test@test.test&password=testtest&type=1”

关于Java (Android),方法 POST,Web 格式而不是 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41238248/

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