【问题标题】:Latin characters break XML Post Request in Java拉丁字符打破 Java 中的 XML Post 请求
【发布时间】: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"));

【问题讨论】:

    标签: java xml utf-8


    【解决方案1】:

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

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

    该类的默认编码是“ISO 8859-1”。我不知道如何将“响应”格式化为 UTF-8,以便仍然返回错误的字符。

    【讨论】:

      猜你喜欢
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 2015-03-24
      • 2011-01-27
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多