2 Steps to jsp send post request and print response data



Step 2: Add demo code in this jsp file

After you have created a jsp file, then you can copy code below into your jsp file.


<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="java.net.HttpURLConnection"%>
<%@ page import="java.net.URL"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.List"%>
<%@ page import="java.io.BufferedReader"%>
<%@ page import="java.io.ByteArrayOutputStream"%>
<%@ page import="java.io.FileOutputStream"%>
<%@ page import="java.io.IOException"%>
<%@ page import="java.io.InputStream"%>
<%@ page import="java.io.OutputStream"%>
<%@ page import="java.io.PrintWriter"%>
<%@ page import="java.net.URLConnection"%>
<%@ page import="java.util.Map"%>

<%
// param
String coordinates= request.getParameter("coordinates");
String target=request.getParameter("target");
String source= request.getParameter("source");

coordinates = (coordinates == null ? "" : coordinates.trim());
target = (target == null ? "" : target.trim());
source = (source == null ? "" : source.trim());

String URL = "http://10.18.54.190:7080/ipark-site/seven/inverse.action";
%>
<%

class CoordHttpRequester {
 public String sendPost(String url, String param) {
 ByteArrayOutputStream out = null;
 InputStream in = null;
 String result = "";
 try {
 URL realUrl = new URL(url);

 HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
 conn.setDoOutput(true);
 conn.setDoInput(true);
 conn.setRequestMethod("POST");

 conn.setConnectTimeout(30 * 1000);
 conn.setReadTimeout(30 * 1000);
 conn.getOutputStream().write(param.getBytes());
 conn.getOutputStream().flush();

 in = conn.getInputStream();
 out = new ByteArrayOutputStream();
 byte[] bufferByte = new byte[1024];
 for (int l = -1; (l = in.read(bufferByte)) > -1;) {
 out.write(bufferByte, 0, l);
 out.flush();
 }
 byte[] dataReturn = out.toByteArray();
 result=new String(dataReturn);
 } catch (Exception e) {
 e.printStackTrace();
 }
 finally {
 try {
 if (out != null) {
 out.close();
 }
 if (in != null) {
 in.close();
 }
 } catch (IOException ex) {
 ex.printStackTrace();
 }
 }
 return result;
 }
}
%>
<%
String s1 = "";
if(!"".equals(coordinates)&& !"".equals(target) && !"".equals(source)){
 // post
 s1= new CoordHttpRequester().sendPost("http://127.0.0.1/online-tools/test.php","coordinates=51,30&target=80&source=54");
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>demo</title>
</head>

<body>
<p><%=s1%></p>
</body>
</html>

Notice and Warning:

1.If you can not get result, you should check this jsp file can be executed at your computer

2.If you can not get result, you also should check the destination url is accessiable or not.