HttpResponse response = client.execute(httpPost);在4.0系统中运行异常的问题

本文详细介绍了在Android 4.0及以上系统中遇到的网络访问权限问题,通过引入StrictMode方法来解决无法在主线程中访问网络的问题,并提供了具体的代码实现。适用于遇到类似问题的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       最近在做一个项目,涉及到网络通信这块,需要向服务器发送请求,获取服务器端的数据,程序在android 2.2系统中运行正常,在4.0系统中运行获取不到数据。

       网上查了下资料,发现 Android在4.0之前的版本 支持在主线程中访问网络,但是在4.0以后对这部分程序进行了优化,访问网络的代码不能写在主线程中了。


       解决方法如下:

       在OnCreate()中加入如下代码:

	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()   // or .detectAll() for all detectable problems
                 .penaltyLog()
                 .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());</span>
		

        问题就解决了,StrictMode方法仅在4.0系统中使用,因此需使用4.0以上的系统。


优化这段代码@PostMapping("/login") @ResponseBody @PassToken public Object login(String username,String password) throws IOException { String url="http://42.177.95.222:9202/platform/yugang/task/getToken"; HttpClient client = HttpClients.createDefault(); //默认post请求 HttpPost post = new HttpPost(url); //拼接多参数 JSONObject json = new JSONObject(); json.put("username", "渔业协会"); json.put("password", "Yuye!@#qwe"); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); String s = EntityUtils.toString(entity); JSONObject jo = JSONObject.parseObject(s); String token = jo.getJSONObject("data").getString("token"); System.out.println("dsadasdasdsadasd"+token); return verify(token); } public Object verify(String token) throws IOException { String url="http://42.177.95.222:9202/platform/yugang/task/verify"; HttpClient client = HttpClients.createDefault(); //默认post请求 HttpPost post = new HttpPost(url); //拼接多参数 JSONObject json = new JSONObject(); json.put("token",token); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); String s = EntityUtils.toString(entity); JSONObject jo = JSONObject.parseObject(s); return jo; }
05-27
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值