gpt4 book ai didi

java - 如何在 Java 中使用 HttpGet 在 REST 调用中传递空格

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:43 26 4
gpt4 key购买 nike

我正在使用他们的 REST API 向 SMS 网关发送调用。当我发送一个像“你好”这样的简单词时一切都很好,但是如果我添加一个空格就会遇到麻烦。这是因为 URI 不能包含空格。

做我需要做的事情的正确方法是什么?

HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.example.com/SecureREST/SimpleSMSsend?PhoneNumber=123&Message=hello how are you?");
httpget.addHeader(new BasicHeader("Accept", "application/json"));

// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
httpclient.getConnectionManager().shutdown();
}

导致 IllegalArgumentException:

Exception in thread "main" java.lang.IllegalArgumentException
at java.net.URI.create(Unknown Source)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
at main.main(main.java:36)
Caused by: java.net.URISyntaxException: Illegal character in query at index 97: https://www.example.com/SecureREST/SimpleSMSsend?PhoneNumber=123&Message=Hello, how are you?
at java.net.URI$Parser.fail(Unknown Source)
at java.net.URI$Parser.checkChars(Unknown Source)
at java.net.URI$Parser.parseHierarchical(Unknown Source)
at java.net.URI$Parser.parse(Unknown Source)
at java.net.URI.<init>(Unknown Source)
... 3 more

编辑:正如 alexey28 所建议的,我正在使用编码器,这是我现在所做的:

String query = "?PhoneNumber=123&Message=Hello, how are you?";
String host = "https://www.example.com/SecureREST/SimpleSMSsend";
String encodedUrl = host + URLEncoder.encode(query,"utf-8");
HttpGet httpget = new HttpGet(encodedUrl);

但是结果是

Exception in thread "main" org.apache.http.client.HttpResponseException: **Bad Request**
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:67)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:54)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:735)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:709)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:700)
at main.main(main.java:47)

我在这里做错了什么?

编码后的请求:执行请求https://www.example.com/SecureREST/SimpleSMSsend%3FPhoneNumber%3D123%26Message%3DHello%2C+how+are+you%3F

最佳答案

在发送之前使用 URLEncoder 对 URL 参数值进行编码:

String restUrl = URLEncoder.encode("You url parameter value", "UTF-8");

它将用正确的 URL 替换所有符号,包括空格 -> '+'

关于java - 如何在 Java 中使用 HttpGet 在 REST 调用中传递空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10602215/

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