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
    关注
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R