拉丁字符在 Java 中会中断 XML Post Request



我有一个有效的 XML POST 请求,直到我更改一个字段以包含拉丁语 UTF-8 字符,例如"Î"。我收到来自该服务的 400 错误响应。

这两个请求都在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 字符这是需要的编辑:

output.write(body.getBytes("UTF-8"));

编辑:我找到了解决方案。这有帮助: Unicode 字符 这是需要的编辑:

output.write(body.getBytes("UTF-8"));

该类的默认编码为"ISO 8859-1"。我没有弄清楚如何将"响应"格式化为 UTF-8,以便仍然返回错误的字符。

最新更新