我有一个可用的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"));
答案 0 :(得分:0)
output.write(body.getBytes("UTF-8"));
该类的默认编码是“ISO 8859-1”。我没弄明白如何将“响应”格式化为UTF-8,以便仍然返回错误的字符。