Java 中使用 JSON 进行 http POST 后的奇怪响应

发布于 2024-11-07 02:17:40 字数 2902 浏览 0 评论 0原文

我正在做一个简单的 http post,其中包含一个 json 字符串作为 http 正文。

?在此处输入图像描述

除了响应本身之外,所有内容看起来都不错 - 当我将其转换为字符串时,它看起来很奇怪(不是文字)。我怎样才能以纯文本形式得到这个?或者我在发帖过程中做错了什么才能得到这个回复? (注意 - 如果我在 POST 期间排除 cookie,我确实会从服务器返回纯 html,并带有有效的“访问被拒绝”消息)

此解决方案的完整代码如下

public class BaseHttpService {
    public ResponseAndCookies doHttpPostWithUrlWithJson(String url, String key, CookieStore cookies) {
        try {
            StringEntity se = new StringEntity("{\"filters\":true}");
            se.setContentType("text/xml");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

            HttpPost httpost = new HttpPost(url);
            httpost.setEntity(se);

            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-Type", "application/json");

            return executeHttpRequest(httpost, cookies);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ResponseAndCookies executeHttpRequest(HttpRequestBase http, CookieStore cookieStore) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String result = "";

        if (cookieStore != null) {
            ((DefaultHttpClient) httpclient).setCookieStore(cookieStore);
        }

        try {
            response = httpclient.execute(http);

            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();
                result = convertStreamToString(instream);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Cookie> cookies = ((DefaultHttpClient) httpclient).getCookieStore().getCookies();
        CookieStore postCookieStore = ((DefaultHttpClient) httpclient).getCookieStore();

        ResponseAndCookies x = new ResponseAndCookies();
        x.setCookies(cookies);
        x.setResponse(result);
        x.setCookieStore(postCookieStore);

        httpclient.getConnectionManager().shutdown();

        return x;
    }

    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

I'm doing what should be a simple http post that includes a json string as the http body.

?enter image description here

All looks good except the response itself - when I turn it into a String it comes back looking strange (not text). How might I get this in plain text? Or what did I do wrong during the post to get this response? (note - if I exclude the cookies during the POST I do get plain html back from the server w/ a valid "access denied" message)

Full code for this solution is below

public class BaseHttpService {
    public ResponseAndCookies doHttpPostWithUrlWithJson(String url, String key, CookieStore cookies) {
        try {
            StringEntity se = new StringEntity("{\"filters\":true}");
            se.setContentType("text/xml");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

            HttpPost httpost = new HttpPost(url);
            httpost.setEntity(se);

            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-Type", "application/json");

            return executeHttpRequest(httpost, cookies);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ResponseAndCookies executeHttpRequest(HttpRequestBase http, CookieStore cookieStore) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String result = "";

        if (cookieStore != null) {
            ((DefaultHttpClient) httpclient).setCookieStore(cookieStore);
        }

        try {
            response = httpclient.execute(http);

            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();
                result = convertStreamToString(instream);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Cookie> cookies = ((DefaultHttpClient) httpclient).getCookieStore().getCookies();
        CookieStore postCookieStore = ((DefaultHttpClient) httpclient).getCookieStore();

        ResponseAndCookies x = new ResponseAndCookies();
        x.setCookies(cookies);
        x.setResponse(result);
        x.setCookieStore(postCookieStore);

        httpclient.getConnectionManager().shutdown();

        return x;
    }

    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

在巴黎塔顶看东京樱花 2024-11-14 02:17:40

您尝试使用看起来的平台编码来读取 UTF-8 字符串。
找出返回响应的内容编码并使用它转换为字符串。

如果您想用 2 行代码替换上面的代码,请告诉我。我为您准备了一个项目,该项目已经负责处理 cookie 和转换内容。

You tried to read an UTF-8 String with the platform encoding it seems.
Find out the Content encoding for the returned response and use that to convert to a string.

Let me know if you want to replace the code above with 2 lines of code. I got a project for you that already takes care of cookies and converting content.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文