【发布时间】:2018-03-16 11:30:20
【问题描述】:
我有一个有效的 XML POST 请求,直到我更改一个字段以包含拉丁 UTF-8 字符,例如“Δ。我收到来自服务的 400 Bad Response。
这两个请求都可以在 Google Chrome 扩展 Postman 中运行。
我假设这与 Java 编码字符或读取数据流的方式有关。以下是我的代码,包括相关库。如何解决这个问题?谢谢!
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import net.valutec.ws.*;
public class CardCallbacks extends ValutecWSCallbackHandler {
private void sendInfoToMaropost(GiftCard please) throws IOException {
URL serverUrl = new URL(TARGET_URL + API_KEY);
URLConnection urlConnection = serverUrl.openConnection();
HttpURLConnection hcon = (HttpURLConnection)urlConnection;
System.out.println(dont.getBarcode());
try {
hcon.setReadTimeout(10000);
hcon.setConnectTimeout(15000);
hcon.setRequestMethod("POST");
hcon.setRequestProperty("Content-Type", "application/xml");
hcon.setRequestProperty("Accept", "application/xml");
hcon.setDoInput(true);
hcon.setDoOutput(true);
String body =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<record>" +
" <orderlineid>fakeorderid</orderlineid>" +
" <encoded-barcode>Î</encoded-barcode>" +
//the request that doesn't work
"</record>";
OutputStream output = new BufferedOutputStream(hcon.getOutputStream());
output.write(body.getBytes());
output.flush();
int responseCode = hcon.getResponseCode();
System.out.println(responseCode);
if(responseCode == 200) {
}
BufferedReader in = new BufferedReader(
new InputStreamReader(hcon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println(response);
in.close();
}
finally {
hcon.disconnect();
}
}
编辑:我找到了解决方案。这有帮助:Unicode Characters 这是需要的编辑:
output.write(body.getBytes("UTF-8"));
【问题讨论】: