java代码分别发送get和post请求。
2018-01-21 22:18
507 查看
/** * 发送get请求 */ public static String sendGet(String url,String param){ String result=""; try { url += "?"+param; URL urlObj = new URL(url); URLConnection connection = urlObj.openConnection(); connection.setRequestProperty("accept", "text/html"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)"); connection.connect(); Map<String, List<String>> map = connection.getHeaderFields(); for(String key:map.keySet()){ System.out.println(key+"---"+map.get(key)); } // 定义输入流来读取URL的内容 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); String line; while((line = bufferedReader.readLine())!=null){ result += "\r\n" + line; } } catch (Exception e) { e.printStackTrace(); } return result; }
/** * 发送post请求 */ public static String sendPost(String url,String param){ String result=""; try { URL urlObj = new URL(url); URLConnection connection = urlObj.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)"); connection.setDoOutput(true); connection.setDoInput(true); PrintWriter printWriter = new PrintWriter(connection.getOutputStream()); printWriter.print(param); printWriter.flush(); // 定义输入流来读取URL的内容 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); String line; while((line = bufferedReader.readLine())!=null){ result += "\r\n" + line; } } catch (Exception e) { e.printStackTrace(); } return result; }
相关文章推荐
- java发送http的get、post请求实现代码
- Java代码中利用httpClient发送post、get请求
- JAVA使用http发送post或get请求实例
- Java发送HTTP的POST和GET方式请求
- [转java发送http的get、post请求]
- java apache commons HttpClient发送get和post请求的学习整理
- java使用HttpURLConnection和HttpClient分别模拟get和post请求以及操作cookies
- Java代码发起HTTP GET和POST请求(URLConnection)
- java代码发送JSON格式的httpPOST请求
- HTTP 笔记与总结(1 )Telnet 分别发送 HTTP GET 和 HTTP POST 请求
- java发送http的get、post请求
- java 发送带Basic Auth认证的http post请求实例代码
- httpclient发送post/get请求,Java后台怎么接受
- java发送http的get、post请求
- Python 使用requests模块发送GET和POST请求的实现代码
- Java发送http请求 (get 与 post方法请求)
- java发送post和get请求(1)---HttpURLConnection方式
- Java中发送Http请求Get、Post
- java发送http的get、post请求
- Java爬虫(一)利用GET和POST发送请求,获取服务器返回信息