Android之用HttpURLConnection参数以XML形式封装的部分关键代码
16lz
2021-01-24
HttpURLConnection参数以XML形式封装
//得到连接 public static HttpURLConnection setRequest(String urlStr) { HttpURLConnection con = null; try { URL url = new URL(urlStr); try { con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Pragma:", "no-cache"); con.setRequestMethod("POST"); con.setRequestProperty("Cache-Control", "no-cache"); con.setRequestProperty("Content-Type", "text/xml"); } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); } return con; }
请求参数xml的封装,以注册为例子
//注册参数 public static String getXmlRegister(String username, String userpwd, String mobile, String email, String sex, String birthday, String address) { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); sb.append("<username>" + username + "</username>"); sb.append("<userpwd>" + userpwd + "</userpwd>"); sb.append("<mobile>" + mobile + "</mobile>"); sb.append("<email>" + username + "</email>"); if (sex != null) { sb.append("<sex>" + sex + "</sex>");//是否必填 否 } if (birthday != null) { sb.append("<birthday>" + birthday + "</birthday>");//是否必填 否 } if (address != null) { sb.append("<address>" + address + "</address>");//是否必填 否 } sb.append("</xml>"); return sb.toString(); }
注册请求代码
//注册请求 public static String postByRegister(String urlStr, String username, String pwd, String mobile, String email, String sex, String birthday, String address) { OutputStreamWriter out = null; String line = ""; BufferedReader in = null; try { HttpURLConnection con = setRequest(urlStr); out = new OutputStreamWriter(con.getOutputStream()); String xmlInfo = getXmlRegister(username, pwd, mobile, email, sex, birthday, address); System.out.println("urlStr=" + urlStr); System.out.println("xmlInfo=" + xmlInfo); out.write(new String(xmlInfo.getBytes("ISO-8859-1"))); out.flush(); out.close(); // 使用输出流来输出字符(可选) if (con.getResponseCode() != 200) throw new RuntimeException("请求url失败"); InputStream is = con.getInputStream();// 获取返回数据 ByteArrayOutputStream baout = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) != -1) { baout.write(buf, 0, len); } line = new String(baout.toByteArray()); System.out.println(line); out.close(); return line; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return line; }
更多相关文章
- 【Android(安卓)应用开发】Activity 状态保存 OnSaveInstanceSta
- android之各种布局控件和对话框
- Android(安卓)获取随机验证码功能示例
- Android(安卓)Retrofit网络框架 (一)
- Android(安卓)里面的android_secret_code
- Android(安卓)OTA升级包制作脚本详解(二,解压缩)
- android 带参数广播示例
- Android(安卓)API demos 阅读笔记 2
- Android读取文件时,由byte转成String字符串时出现乱码