首页 > 代码库 > Http访问网络之GET和POST
Http访问网络之GET和POST
public class HttpGetUtil { // 用get请求获取输入流 public static InputStream getInputStream() { InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try { URL url = new URL("http://www.baidu.com/img/bd_logo1.png"); if (url != null) { httpURLConnection = (HttpURLConnection) url.openConnection(); // 设置连接网络的超时时间 httpURLConnection.setConnectTimeout(3000); // 打开输入流 httpURLConnection.setDoInput(true); // 使用GET方法请求 httpURLConnection.setRequestMethod("GET"); // 获取结果响应码 int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { inputStream = httpURLConnection.getInputStream(); } } } catch (Exception e) { e.printStackTrace(); } return inputStream; } // 将输入流存在本地 public void saveImageToDisk() { InputStream inputStream = getInputStream(); byte[] data = http://www.mamicode.com/new byte[1024];>
public class HttpPostUtil { private static URL url; // 用post请求获取输入流 public static String sendPostMessage(Map<String, String> params, String encode) { // 初始化 StringBuffer buffer = new StringBuffer(); buffer.append("?"); try { if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { // 完成转码 buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)) .append("&"); } // 删掉最后一个& buffer.deleteCharAt(buffer.length() - 1); } HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(3000); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true);// 从服务器获取数据 urlConnection.setDoOutput(true);// 向服务器写数据 // 获得上传信息的字节大小以及长度 byte[] mydata = http://www.mamicode.com/buffer.toString().getBytes();>Http访问网络之GET和POST
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。