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

2022-09-04 00:58:41

我正在使用 SMS 网关的 REST API 向其发送调用。当我发送一个简单的单词(如“Hello”)时,一切都很好,但是如果我添加一个空格,那么我就遇到了麻烦。这是因为 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();
}

在非法争论异常上的结果:

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


答案 1

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

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

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


答案 2