android 发送http请求
16lz
2022-01-09
好久没写博客了,因为公司要做android,笔者也是第一次接触。
这是在项目中遇到一个比较麻烦的问题,记录下来备忘(本人刚接触,有不对的地方请指教)。
发送请求的代码:
package com.jiujian.mperdiem;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class AppUtil { // 本地测试路径 public static final String webBaseUrl = "http://ip:端口"; /* * 访问URL,获取结果 method: GET, POST */ public static String loadUrlResponse(String method, String urlString) { HttpURLConnection conn = null; // 连接对象 InputStream is = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(urlString); // URL对象 conn = (HttpURLConnection) url.openConnection(); // 使用URL打开一个链接 conn.setDoInput(true); // 允许输入流,即允许下载 conn.setDoOutput(true); // 允许输出流,即允许上传 conn.setUseCaches(false); // 不使用缓冲 conn.setRequestMethod(method); // 使用get请求 is = conn.getInputStream(); // 获取输入流,此时才真正建立链接 InputStreamReader isr = new InputStreamReader(is); BufferedReader bufferReader = new BufferedReader(isr); String inputLine = ""; while ((inputLine = bufferReader.readLine()) != null) { result.append(inputLine).append("\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (conn != null) { conn.disconnect(); } } return result.toString(); }}
调用代码:
StringBuffer sbUpdateDeviceRefreshInstall = new StringBuffer(AppUtil.webBaseUrl);sbUpdateDeviceRefreshInstall.append("XXX?UserId=");sbUpdateDeviceRefreshInstall.append(getUserId());AppUtil.loadUrlResponse("POST", sbUpdateDeviceRefreshInstall.toString());
代码是没有问题的,可是app端发送请求,server端却一直没有打印信息。
错误信息是:android.os.NetworkOnMainThreadException
最后才发现android 3.0以后就不允许在主线程上进行网络访问的,
于是把代码改成:
new Thread(){ @Override public void run() { StringBuffer sbUpdateDeviceRefreshInstall = new StringBuffer(AppUtil.webBaseUrl); sbUpdateDeviceRefreshInstall.append("XXX?UserId="<span style="font-family: 'Microsoft YaHei';">);</span> sbUpdateDeviceRefreshInstall.append(getUserId()); AppUtil.loadUrlResponse("POST", sbUpdateDeviceRefreshInstall.toString()); } }.start();
这样就没问题了。
如果是刚接触android,可以推荐看:第一行代码,这本书对于入门来说挺不错的。
更多相关文章
- Android(安卓)中各种XML文件的作用
- Android第五十二期 - 云之讯的代码混淆
- Android中的strings文件中字符串的拼接
- Android(安卓)startActivityForResult的使用
- Android代码风格指导
- Android学习心得(六)——位置服务
- Android(安卓)调用系统Camera
- Android(安卓)WebView 支持H5图片上传
- Http的15种请求