[英]Send a String using Java Servlet over HTTP request
嗨,我正在嘗試實現一個服務器,該服務器接受一個字符串,然后生成並向客戶端返回另一個字符串,但是運行不正常。
這是我嘗試過的:服務器:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
....
String str = "something";
// Return the queueId.
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write(str);
writer.flush();
writer.close();
}
客戶:
String URL = "http://localhost:8080/"
String serverURL = URL + "servlet?param=" + someParam;
final URL url = new URL(serverURL)
final URLConnection connection = url.openConnection();
connection.setDoOutput(true);
final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
System.out.println(br.readLine());
但是br.readLine()以某種方式返回null。 在這種情況下哪一方錯?
提前致謝。
您的客戶應進行以下更改。 由於您使用的是doPOST
而不是doGet
String URL = "http://localhost:8080/"
String serverURL = URL + "servlet?param=" + someParam;
final URL url = new URL(serverURL)
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
System.out.println(br.readLine());
您的代碼可能正在調用doGet
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.