- 2023-05-18 16:19:27
- 6256 热度
- 0 评论
HTTP发送的数据有两种方式,一种是GET请求,一种是POST请求,GET请求就是简单的URL拼接参数,发送的参数长度也有限制。
而POST的参数可以设置在FORM中,参数长度也可以满足大多要求,有时从服务器的性能上考虑,防止恶意的GET尝试,很多接口都是限制POST方式的。
那么POST请求发送参数来说常用也有两种方式,一种是拼接参数和GET一样,但是发送方式指定为POST。
发送的数据不同,也可以在头上进行指定,这里的示例基于HttpClient(相关介绍参考:HttpClients下载与入门)。
这里也写个简单GET请求:
/** * Get请求 */ public static String HttpGet(String url) throws Exception{ String jsonString = ""; HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true)); client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); //通过网络与服务器建立连接的超时时间 client.getHttpConnectionManager().getParams().setSoTimeout(60000); //Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间 GetMethod method = new GetMethod(url); method.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); try { client.executeMethod(method); jsonString = method.getResponseBodyAsString(); } catch (Exception e) { jsonString = "error"; logger.error("HTTP请求路径时错误:" + url, e.getMessage()); throw e; // 异常外抛 } finally { if (null != method) method.releaseConnection(); } return jsonString; }
POST请求我们使用URLConnection来写:
public static String sendPost(String url, String param) throws Exception{ PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(10*1000); conn.setDoOutput(true); // 发送POST请求必须设置如下两行 conn.setDoInput(true); out = new PrintWriter(conn.getOutputStream()); out.print(param); out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { logger.error("HTTP请求路径时错误:" + url, e.getMessage()); throw e; // 异常外抛 } finally{ try{ if(out!=null)out.close(); if(in!=null) in.close(); } catch(Exception ex){ } } return result; }
此时,同一个连接,调用不同的方法,就是不同的发送方式。
服务器端接收的话可以参照这样,基于SpringMVC的写法:
@SuppressWarnings({ "unchecked" }) @RequestMapping(value="/testPost2",method = RequestMethod.POST) public ResponseEntity<String> testPost2(HttpServletRequest req,HttpServletResponse res, @RequestParam(value="postXML") String postXML) throws Exception{ System.out.println(postXML); Document docRe = DocumentHelper.createDocument(); Element SyncAppOrderResp = docRe.addElement("reXML").addNamespace("", "http://www.javacui.com/xml/schemas/"); SyncAppOrderResp.addElement("status").addText("0"); return new ResponseEntity(docRe.asXML(), HttpStatus.OK); }
以上的写法,POST的参数是基于KEY和VALUE方式的,还有一种普遍做法是把参数XML直接写在头里面。
此时的写法就是把要发送的参数写在RequestBody里面,执行发送的内容是基于什么格式的,例如下面的示例,普通发送,JSON和XML:
/** * 普通POST请求 */ @SuppressWarnings("deprecation") public static String HttpPost(String url, String body) throws Exception{ String jsonString = ""; HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true)); client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); //通过网络与服务器建立连接的超时时间 client.getHttpConnectionManager().getParams().setSoTimeout(60000); //Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间 PostMethod method = new PostMethod(url); method.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); method.setRequestBody(body); try { client.executeMethod(method); jsonString = method.getResponseBodyAsString(); } catch (Exception e) { jsonString = "error"; logger.error("HTTP请求路径时错误:" + url, e.getMessage()); throw e; // 异常外抛 } finally { if (null != method) method.releaseConnection(); } return jsonString; } /** * JSON的POST请求 */ @SuppressWarnings("deprecation") public static String HttpPostJSON(String url, JSONObject body) throws Exception{ String jsonString = ""; HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true)); client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); //通过网络与服务器建立连接的超时时间 client.getHttpConnectionManager().getParams().setSoTimeout(60000); //Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间 client.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); PostMethod method = new PostMethod(url); method.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); method.setRequestBody(body.toString()); try { client.executeMethod(method); jsonString = method.getResponseBodyAsString(); } catch (Exception e) { jsonString = "error"; logger.error("HTTP请求路径时错误:" + url, e.getMessage()); throw e; // 异常外抛 } finally { if (null != method) method.releaseConnection(); } return jsonString; } /** * XML的POST请求 */ @SuppressWarnings("deprecation") public static String HttpPostXml(String url, String xmlBody) throws Exception{ String result = ""; HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true)); client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); //通过网络与服务器建立连接的超时时间 client.getHttpConnectionManager().getParams().setSoTimeout(60000); //Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间 PostMethod method = new PostMethod(url); method.setRequestHeader("Content-Type", "application/xml"); if(null != xmlBody){ method.setRequestBody(xmlBody); } try { client.executeMethod(method); result = method.getResponseBodyAsString(); } catch (Exception e) { result = "error"; logger.error("HTTP请求路径时错误:" + url, e.getMessage()); throw e; // 异常外抛 } finally { if (null != method) method.releaseConnection(); } return result; }
而服务器端接收时,就需要从头中获取参数,代码参考:
@SuppressWarnings({ "unchecked" }) @RequestMapping(value="/testPost1",method = RequestMethod.POST) public ResponseEntity<String> testPost1(HttpServletRequest req,HttpServletResponse res) throws Exception{ BufferedReader bufferReader = req.getReader();//获取头部参数信息 StringBuffer buffer = new StringBuffer(); String line = " "; while ((line = bufferReader.readLine()) != null) { buffer.append(line); } String postData = buffer.toString(); System.out.println(postData); Document docRe = DocumentHelper.createDocument(); Element SyncAppOrderResp = docRe.addElement("reXML").addNamespace("", "http://www.javacui.com/xml/schemas/"); SyncAppOrderResp.addElement("status").addText("0"); return new ResponseEntity(docRe.asXML(), HttpStatus.OK); }
testPost1和testPost2这两种方式,我们可以写一个MAIN来测试:
public static void main(String[] args) { try { System.out.println(HttpPostXml("http://localhost:8008/api/testPost1", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><status>1</status></root>")); System.out.println(sendPost("http://localhost:8008/api/testPost2", "postXML=<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><status>1</status></root>")); } catch (Exception e) { e.printStackTrace(); } }
发送接收的都是XML参数,发送和接收打印在控制台。
0 评论
留下评论
热门标签
- Spring(403)
- Boot(208)
- Spring Boot(187)
- Spring Cloud(82)
- Java(82)
- Cloud(82)
- Security(60)
- Spring Security(54)
- Boot2(51)
- Spring Boot2(51)
- Redis(31)
- SQL(29)
- Mysql(25)
- IDE(24)
- Dalston(24)
- MVC(22)
- JDBC(22)
- IDEA(22)
- mongoDB(22)
- Web(21)
- CLI(20)
- SpringMVC(19)
- Alibaba(19)
- Docker(17)
- SpringBoot(17)
- Git(16)
- Eclipse(16)
- Vue(16)
- ORA(15)
- JPA(15)
- Apache(15)
- Tomcat(14)
- Linux(14)
- HTTP(14)
- Mybatis(14)
- Oracle(14)
- jdk(14)
- Pro(13)
- XML(13)
- JdbcTemplate(13)
- OAuth(13)
- Nacos(13)
- Data(12)
- JSON(12)
- OAuth2(12)
- Myeclipse(11)
- stream(11)
- int(11)
- not(10)
- Bug(10)
- Hystrix(9)
- ast(9)
- maven(9)
- Map(9)
- Swagger(8)
- APP(8)
- Bit(8)
- API(8)
- session(8)
- Window(8)
- HTML(7)
- Github(7)
- JavaMail(7)
- Cache(7)
- File(7)
- IntelliJ(7)
- mail(7)
- windows(7)
- too(7)
- ehcache(6)
- UDP(6)
- RabbitMQ(6)
- and(6)
- star(6)
- Excel(6)
- Log4J(6)
- pushlet(6)
- apt(6)
- read(6)
- Freemarker(6)
- WebFlux(6)
- JSP(6)
- Bean(6)
- error(6)
- nginx(6)
- Server(6)
- jar(6)
- ueditor(6)
- Sentinel(5)
- the(5)
- JWT(5)
- rdquo(5)
- PHP(5)
- Struts(5)
- string(5)
- script(5)
- Syntaxhighlighter(5)
- Tool(5)
- Controller(5)
- swagger2(5)