Android Studio中与网站通信
16lz
2021-01-23
post方法
HttpURLConnection必须在子线程执行
/** * 方法名: new Thread * 作用: 开启新的子线程, * start(): 是准备运行子线程 * run(): 运行子线程 */ new Thread(new Runnable() { @Override public void run() { String path = "https://网址"; //要提交的网址,如果是http需要android:usesCleartextTraffic="true" try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //得到conn对象 conn.setConnectTimeout(60000); //连接服务器超时 conn.setRequestMethod("POST"); //设置请求模式 conn.setReadTimeout(60000); //从服务器接收数据超时 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 设置发送的数据为表单类型,会被添加到http body当中 //conn.setRequestProperty ("Content-Type", "application/json"); Gson gson = new Gson(); Person person = new Person(); person.setCha_xun("ceshi"); person.setKai_shi_shi_jian(shu_zi); String data = gson.toJson(person); //将对象转换为JSON conn.setRequestProperty("Content-Length", String.valueOf(data.length()));//设置发送数据的长度 conn.setDoOutput(true); //设置true表示连接为输出(提交),默认为false. conn.setUseCaches(false); //设置不用缓存 conn.setDoInput(true); //设置true表示连接为输入(提交),默认为true. conn.getOutputStream().write(data.getBytes()); //写入此连接的输出流,我理解为提交数据 int responseCode = conn.getResponseCode(); //从HTTP响应消息获取状态代码 if (responseCode == 200) { InputStream inputStream = conn.getInputStream(); //从这个打开的连接读取数据的输入流(读取服务器返回的数据) final String result = StreamUtils.readStream(inputStream); //解析数据 runOnUiThread(new Runnable() { //在子线程操作UI更新的方法 @Override public void run() { textView_cha_xun_fan_hui.setText(result); } }); } else { showToastInAnyThread("保存失败"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start();
StreamUtils类
public class StreamUtils { public static String readStream(InputStream is){ try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while(( len = is.read(buffer))!=-1){ baos.write(buffer, 0, len); } is.close(); String result = baos.toString(); if(result.contains("gb2312")){ return baos.toString("gb2312"); }else{ return result; } } catch (Exception e) { e.printStackTrace(); return null; } } public static Bitmap readBitmap(InputStream is){ return BitmapFactory.decodeStream(is); }}
更多相关文章
- android中清空一个表---类似truncate table 表名 这样的功能 and
- Android 5种方式存储数据:
- 基于TCP和多线程实现无线鼠标键盘-Socket(2)
- android中在子线程中更新UI的几种方法
- 工程 android上传图片至服务器
- android利用handler线程间的通信
- 关于Android在非UI线程更新UI的问题。