首页 / JAVA / java Http请求
java Http请求
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java Http请求,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2575字,纯文字阅读大概需要4分钟。
内容图文
1. 发送get请求
/** * 发送GET请求 * * @param urlStr 目的地址 * @param params 请求参数,Map类型。 * @return 远程响应结果 */ public String sendGet(String urlStr, Map<String, String> params) throws Exception { //拼接urlStr StringBuffer sb = new StringBuffer(); for(Entry<String, String> entry : params.entrySet()) { sb.append("&").append(entry.getKey()).append("=").append(entry.getValue()); } sb.replace(0, 1, "?"); sb.insert(0, urlStr); //创建url对象 URL url = new URL(sb.toString()); //创建连接对象,我们要使用http连接 所以强转为Http连接对象 HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); //连接对象设置通用参数 httpConnection.setRequestProperty("Accept", "*/*"); httpConnection.setRequestProperty("Connection", "Keep-Alive"); httpConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); //建立连接 httpConnection.connect(); // 获取响应头信息 Map<String, List<String>> headers = httpConnection.getHeaderFields(); //获取响应内容 BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "UTF-8")); sb = new StringBuffer(); String line = null; while((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); }
2. 发送post请求
/** * 发送POST请求 * * @param urlStr 目的地址 * @param params 请求参数,Map类型。 * @return 远程响应结果 */ public String sendPost(String urlStr, Map<String, String> params) throws Exception { StringBuffer sb = new StringBuffer(); for(Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } sb.substring(sb.length() - 1, sb.length()); System.out.println(sb.toString()); //创建url对象 URL url = new URL(urlStr); //创建连接对象,我们要使用http连接 所以强转为Http连接对象 HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); //连接对象设置通用参数 httpConnection.setRequestProperty("Accept", "*/*"); httpConnection.setRequestProperty("Connection", "Keep-Alive"); httpConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); // 设置POST方式 httpConnection.setDoInput(true); httpConnection.setDoOutput(true); // 获取HttpURLConnection对象对应的输出流 PrintWriter out = new PrintWriter(httpConnection.getOutputStream()); // 发送请求参数 out.write(sb.toString()); // flush输出流的缓冲 out.flush(); //获取响应内容 BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "UTF-8")); sb = new StringBuffer(); String line = null; while((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); }
原文:https://www.cnblogs.com/zhangzonghua/p/12870213.html
内容总结
以上是互联网集市为您收集整理的java Http请求全部内容,希望文章能够帮你解决java Http请求所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。