android 关于HttpURLConnection 抛出了异常




    private String url = "http://www.baidu.com";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //从网络获取数据
                String msgs = get(url);
            }
        }).start();
    }

    public  String get(String url) {
        HttpURLConnection conn = null;
        try {
            // 利用string url构建URL对象
            URL mURL = new URL(url);
            conn = (HttpURLConnection) mURL.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);

            int responseCode = conn.getResponseCode();
            String msg = getString(responseCode);
            Log.i("msg",msg);
            if (responseCode == 200) {

                InputStream is = conn.getInputStream();
                String response = getStringFromInputStream(is);
                return response;
            } else {
                throw new NetworkErrorException("response status is "+responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (conn != null) {
                conn.disconnect();
            }
        }

        return null;
    }
代码如上,拿百度网址测试是没问题的,是可以到getInputStream的,也显示出responseCode是200   ;  connected 也是true
拿自己服务器的url测试就出了问题,在执行getResponseCode时就会抛出异常![跳转抛出异常](https://img-ask.csdn.net/upload/201605/29/1464464089_453718.png),但是connected情况是true的![](https://img-ask.csdn.net/upload/201605/29/1464464132_966673.png)

这个错误是因为什么呢```

抱歉,补上自己的url测试时的问题的图片
执行getResponseCode时就会抛出异常
执行getResponseCode时就会抛出异常
connected情况是true的
connected情况是true的

responsecode已经反应出错误了。你可以先看看你服务器上是否接受到请求。然后是否正确返回html内容

你可以用postman之类的工具测一下你的webservice,200系列都对应成功的,你没必要抛出异常,另外,自己的测试环境的话,URL可不要放localhost之类的,指向的是手机自身,模拟器好像更麻烦。看你的情况,像是压根没连上,你可以联调看服务端log,有没有请求过来。

responseCode 不是 为 -1 吗?

看一下自己的服务器,还有编码格式

看一下自己的服务器,还有编码格式