作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在使用他们的 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)
我在这里做错了什么?
最佳答案
在发送之前使用 URLEncoder 对 URL 参数值进行编码:
String restUrl = URLEncoder.encode("You url parameter value", "UTF-8");
它将用正确的 URL 替换所有符号,包括空格 -> '+'
关于java - 如何在 Java 中使用 HttpGet 在 REST 调用中传递空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10602215/
我是一名优秀的程序员,十分优秀!