私には達成しようとしていることがあります。
ポート 8080 のローカルホストで Web アプリケーションを実行しています。
localhost:9005 で HTTP サーバーを実行しています。
サーブレット Java クラスに情報を渡す JSP フォームがあります。これは、データ文字列を使用して、HTTP サーバー localhost:9010 の URL に HTTP ポストを実行します。
私がする必要があるのは、同じ接続の一部として POST と GET を実行することです。私はそれらを2つの別々の呼び出しとして機能させていますが、同じ接続ではありません。データを投稿すると、同じ接続である必要があります。HTTP サーバーはこのデータを取得して処理し、一意のデータをこの URL に出力します。したがって、GET は POST と同じ接続の一部である必要があります。
誰でも助けてもらえますか?
これは私のプロセスリクエストのJavaコードです:
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.List;
import java.util.Map.Entry;
public class ProcessRequest {
public void sendRequestToGateway() throws Throwable{
String message = URLEncoder.encode("OP1387927", "UTF-8");
try {
URL url = new URL("http://localhost:9005/json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("operator=" + message);
writer.close();
System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
receiveMessageFromGateway();
} else {
// Server returned HTTP error code.
}
//receiveMessageFromGateway();
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
}
public void receiveMessageFromGateway() throws Throwable {
HttpURLConnection client = null;
OutputStreamWriter wr = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
try {
URL url = new URL("http://localhost:9005/json");
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("GET");
client.setDoOutput(true);
client.setReadTimeout(10000);
client.connect();
System.out.println(" *** headers ***");
for (Entry<String, List<String>> headernew : client.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
}
System.out.println(" \n\n*** Body ***");
rd = new BufferedReader(new InputStreamReader(client.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println("body=" + sb.toString());
} finally {
client.disconnect();
rd = null;
sb = null;
wr = null;
}
}
}