使用URLConnection发送GET和POST请求的简单示例
2015-12-08 17:20
543 查看
Get请求
POST请求
import java.net.URLConnection; public class HttpGet { public static void main(String[] args) throws Exception { final String spec = "http://192.168.0.115:20000/test/test.json?item=123"; URL url = new URL(spec); URLConnection connection = url.openConnection(); HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.setRequestProperty("Accept-Charset", "utf-8"); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (httpURLConnection.getResponseCode() == 200) { try (BufferedReader reader = new BufferedReader( new InputStreamReader( httpURLConnection.getInputStream()))) { String tempLine = null; StringBuffer resultBuffer = new StringBuffer(); while ((tempLine = reader.readLine()) != null) { resultBuffer.append(tempLine); } System.out.println(resultBuffer.toString()); } } } }
POST请求
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class HttpPost { public static void main(String[] args) throws Exception { final String spec = "http://192.168.0.115:20000/test/test.json"; URL url = new URL(spec); URLConnection connection = url.openConnection(); HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.setRequestProperty("Accept-Charset", "utf-8"); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter( httpURLConnection.getOutputStream())) { outputStreamWriter.write("item=123"); outputStreamWriter.flush(); } Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields(); for ( Entry<String, List<String>> entry : headerFields.entrySet()) { System.out.println(entry.getKey()); for (String value : entry.getValue()) { System.out.println("\t" + value); } } if (httpURLConnection.getResponseCode() == 200) { try (BufferedReader reader = new BufferedReader( new InputStreamReader( httpURLConnection.getInputStream()))) { String tempLine = null; StringBuffer resultBuffer = new StringBuffer(); while ((tempLine = reader.readLine()) != null) { resultBuffer.append(tempLine); } System.out.println(resultBuffer.toString()); } } } }
相关文章推荐
- RPC failed; result=22, HTTP code = 411
- HTTP Header 属性列表
- nginx中http核心模块的配置指令2
- nginx中http核心模块的配置指令3
- nginx中http核心模块的配置指令4
- nginx中http的fastcgi模块的配置指令1
- 如何在 Linux 中快速地通过 HTTP 提供文件访问服务
- 深入HTTP head的使用详解
- ASP 中使用 HTTP 协议发送参数详解
- C#基于socket模拟http请求的方法
- http www安全必备知识
- asp HTTP 500错误 常见问题分析
- http代理相关知识分析
- 在Node.js中使用HTTP上传文件的方法
- php错误提示failed to open stream: HTTP request failed!的完美解决方法
- php提示Failed to write session data错误的解决方法
- PHP5.5和之前的版本empty函数的不同之处
- PHP实现支持GET,POST,Multipart/form-data的HTTP请求类