14

我正在使用他们的 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

4

1 回答 1

25

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

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

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

于 2012-05-15T13:57:09.437 回答