欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

http post请求和响应(以及模拟接收代码)

程序员文章站 2022-05-07 12:08:18
...
/**
	 * 向服务器发送post请求
	 * @param httpUrl  请求地址
	 * @param xml   请求xml参数
	 * @return  响应xml参数
	 */
	public static String postRequest(String httpUrl,String xml){
		
		String response = "";
		
		URL url = null;
		try {
			url = new URL(httpUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");// 提交模式
			conn.setRequestProperty("Content-length", String.valueOf(xml.length()));
			conn.setRequestProperty("Content-type", "text/xml");
			conn.setDoOutput(true);
			
			OutputStreamWriter out = new OutputStreamWriter(conn
	                    .getOutputStream());  
			
			out.write(xml);
			out.flush();
			out.close();
			
			int code = conn.getResponseCode();// 从 HTTP 响应消息获取状态码
			
			logger.info("从 HTTP 响应消息获取状态码:"+code);
			
			BufferedReader br = new BufferedReader(new InputStreamReader(conn
                    .getInputStream()));
			String temp = "";
			while((temp = br.readLine())!=null ){
				
				response += temp;
			}
			
		} catch (MalformedURLException e) {
			
			logger.error("执行HTTP post请求时发生异常!", e); 

		} catch (IOException e) {
			logger.error("执行HTTP post请求" + url + "时,发生异常!", e); 

		}
		
		
		return response;
	}

 

这是http post方法请求的封转代码,现在贴上模拟接收请求的响应Action端代码。

	/**
	 * 模拟对方接受请求
	 * @param input
	 * @return
	 */
	@Action("testxml")
	public String responceXml(){
		
		logger.info("********");
		HttpServletRequest request = ServletActionContext.getRequest (); 
		
		String responsexml = "";
		
		HttpServletResponse response = ServletActionContext.getResponse();
		logger.info("responsexml:"+responsexml);
		
		
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(request.getInputStream()));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	       String temp = "";
			try {
				while((temp = br.readLine())!=null ){
					
					responsexml += temp;
				}
				
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
		System.out.println(responsexml);
		response.setContentType("text/xml");
		response.setContentLength(responsexml.length());
		
		try {
			response.getOutputStream().write(responsexml.getBytes());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
		return null;
	}

 

   调用测试用例:

   ScreenDeleteVedioInter是调用接口类,

              @Autowired
	ScreenDeleteVedioInter sd;

              @Action("testresquest")
	public String testResquest(){
		
		List<Integer> list = new ArrayList<Integer>();
		
		list.add(23);
		list.add(24);
		list.add(25);
		
		
		List<String> goList =  sd.screenDeleteReguest(list);
		
		for(int i=0;i<goList.size();i++){
			
			System.out.println(goList.get(i));
			
		}
		
		return null;
	}
	

  昨天写了好久,也遇到不少问题,现在发布代码,便于以后参考,哈哈