java garbage problem solving using URLConnection request

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/u013513053/article/details/100598602

In my service routine, go back to other service program call interface, this tool will need a Http request. I'm using URLConnection. Simple and little packages get and post request method.

In the request, I encountered two problems are associated with the character encoding.

First, the request to another server, the other server can not resolve.

When I run this case the main method used when it is normal, but when I deploy to tomcat after dying. This time I also began to suspect that the problem of coding, coding directly to tomcat, discovered that in fact my coding is UTF-8. Then there is that Baidu search URL encoded in a Chinese, but I am a post, Chinese itself was due to be sent in the past. In say, the server is the people, and they said used properly, does not intend to use the URL encoding and decoding data parsing, then how can I do.
Finally capture discovered that I was indeed sent out garbled, the problem lies on request. After the final positioning of the above method to writ, to modify the character output UTF-8, the problem is resolved. The bottom complete code reference

out = new DataOutputStream(conn.getOutputStream());
 // 发送请求参数(param是String类型)
out.write(param.getBytes("UTF-8"));

Second, when the results get returned, I can not parse

After requesting me not resolve data, regardless of the main method or after tomcat start, get all garbled. Obviously, this is a character encoding problem. From an environmental perspective, are set to UTF-8, the problem still appears in the code level.
After obtaining investigation modify the input stream above, specifies the character encoding is UTF-8, the problem is solved. The complete code with reference to the bottom.

BufferedReader in = null;
 ····省略代码···
in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));

I attach the package code of the post method, the code is also a reference to some online content, but also be modified. Some inappropriate places or areas for improvement, please exhibitions. There is a network request java framework OKHttp, then we will look better than building his own strong wheels. If there are other better tools for network requests, please recommend a wave in this thanked

public  String sendPost(String url, String param) {
        DataOutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL((base+ url).replaceAll(" ",""));
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (connectTimeout != null && connectTimeout > 0) {
                conn.setConnectTimeout(connectTimeout);
            }
            // 获取URLConnection对象对应的输出流
            out = new DataOutputStream(conn.getOutputStream());
            // 发送请求参数
            out.write(param.getBytes("UTF-8"));
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

Guess you like

Origin blog.csdn.net/u013513053/article/details/100598602