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个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐