android中Http访问时 connection.getResponseCode()不被执行,且报错 org.json.JSONException: End of input at charact...

问题:用 android 4.4 写android访问http时,到connection.getResponseCode() 就不被执行,也不报错:但是抛出org.json.JSONException: End of input at character 0 of .异常:

连接代码:

public static String getJsonContent(String url_path){
    try {
        System.out.println("url_path---->>:"+url_path);
        URL url=new URL(url_path);
        HttpURLConnection connetion=(HttpURLConnection)url.openConnection();
        connetion.setConnectTimeout(3000);
        connetion.setRequestMethod("GET");
        connetion.setDoInput(true);
        System.out.println("connetion---->>:"+connetion);
        int code=connetion.getResponseCode();
        System.out.println("code---->>>:"+code);
        if (code==200){
            
            return changeInputStream(connetion.getInputStream());
        }else{
            System.out.println("---->>请求码不正确!!!");
            return "";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
View Code

此段代码直接在java 工程里是可以访问http的,并且用浏览器直接访问 url_path=http://192.168.111.102:8080/jsonproject/servlet/JsonAAction?action_flag=person 也是有相应的,证明url地址是对的。


解决方法:
  原因:访问HTTP的请求没有放在单独线程而是放在 主线程 了。
解决方法,把http的请求单独放在一个新线程中,或者在调用此Http访问的Activity的onCreat()方法内加:closeStrictMode().
  
public static void closeStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build());
}
  参考文章:http://hb.qq.com/a/20110914/000054.htm

转载于:https://www.cnblogs.com/lonsine/p/4524690.html

你可能感兴趣的:(android中Http访问时 connection.getResponseCode()不被执行,且报错 org.json.JSONException: End of input at charact...)