howard_chen 2016-06-22 14:48 采纳率: 0%
浏览 1343

HttpURLConnection做通讯, get方式带中文参数通讯失败

android中用HttpURLConnection做通讯, get方式带中文参数,在 android5.0以下的手机通讯失败,在android5.0以上的手机通讯成功
代码如下
/**
* Get请求,获得返回数据
*
* @param urlStr
* @return
* @throws Exception
/
public static String doGet(String urlStr) {
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
LogUtils.i("urlStr = ",urlStr);
url = new URL(urlStr);
LogUtils.i("url = ",url.toString());
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT_MILLIONS);
conn.setConnectTimeout(CONN_TIMEOUT_MILLIONS);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept", "
/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// conn.setRequestProperty("Accept-Charset", "UTF-8");
// conn.setRequestProperty("Accept-Language","zh-CN");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[1024];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.flush();
            return baos.toString();
        } else {
            // throw new RuntimeException(" responseCode is not 200 ... ");
            String msg = "獲取數據失敗,返回網絡代碼:" + conn.getResponseCode();
            // String jsonstr = "{'status':'false';'msg':'"+msg+"'}";
            String jsonstr = "{'errno': 0,'message':'" + msg + "'}";
            return jsonstr;
        }

    } catch (Exception e) {
        // e.printStackTrace();
        // return "網絡連接失敗或超時";
        String msg = "網絡連接失敗或超時";
        // String jsonstr ="{'status':'false';'msg':'"+msg+"'}";
        String jsonstr = "{'errno': 0,'message':'" + msg + "'}";
        return jsonstr;
    } finally {
        try {
            if (is != null) {
                is.close();
                is = null;
            }
        } catch (IOException e) {
        }
        try {
            if (baos != null) {
                baos.close();
                baos = null;
            }
        } catch (IOException e) {
        }
        conn.disconnect();
    }

    // return null;

}
  • 写回答

1条回答 默认 最新

  • threenewbee 2016-06-22 14:57
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?