Client.java 将字符串发送到servlet
String url = "http://localhost:8084/Lab/url";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
dos = new DataOutputStream(con.getOutputStream());
dos.writeBytes(resultJson.toString());
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
dos.flush();
dos.close();
in.close();
的Servlet 从客户端获取值并返回
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
我不知道接下来该做什么。
答案 0 :(得分:1)
尝试以下方法:
String url = "[http://localhost:8084/Lab/url]";
替换为 String url = "[http://localhost:8084/Lab/url?str=YOURSTRING]";
在[1]中使用 GET ,我们在包含字符串的URL中传递“str”参数。
我们使用servlet [2]中的getParameter()
检索消息。
正如@Anders所说,我们也可以使用 POST
来做到这一点我希望这有用。
干杯
PS:URLS没有[]
的 [UPDATE] 强>
使用POST发送参数
String param = "str=YOURSTRING";
String request = "http://localhost:8084/";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length));
connection.setUseCaches (false);
DataOutputStream out = new DataOutputStream(connection.getOutputStream ());
out.writeBytes(param);
out.flush();
out.close();
connection.disconnect();