如何从 Java 中的 POST 请求获取表单数据
How to get form data from POST request in Java
如何从 POST 请求中提取表单数据,例如。 $ curl -X POST -d asdf=blah http://localhost:8000/proxy/http://httpbin.org/post - 我需要提取 asdf=blah.
我目前的做法在很大程度上依赖于我阅读的特定格式的数据(我假设表单数据始终位于最后一行)。是否有更好的(and/or 更简单)的方式来获取不依赖于所读取数据格式的数据?
(注意:代理同时处理 GET 和 POST 请求)
这是我写的代码:
public class ProxyThread3 extends Thread {
private Socket clientSocket = null;
private OutputStream clientOutputStream;
private static final int BUFFER_SIZE = 32768;
public ProxyThread3(Socket socket) {
super("ProxyThread");
this.clientSocket = socket;
}
public void run() {
try {
clientOutputStream = clientSocket.getOutputStream();
// Read request
InputStream clientInputStream = clientSocket.getInputStream();
byte[] b = new byte[8196];
int len = clientInputStream.read(b);
String urlToCall = "";
if (len > 0) {
String userData = new String(b, 0, len);
String[] userDataArray = userData.split("\n");
//Parse first line to get URL
String firstLine = userDataArray[0];
for (int i = 0; i < firstLine.length(); i++) {
if (firstLine.substring(i).startsWith("http://")) {
urlToCall = firstLine.substring(i).split(" ")[0];
break;
}
}
//get request type
String requestType = firstLine.split(" ")[0];
String userAgentHeader = "";
//get USER-AGENT Header and Accept Header
for (String data : userDataArray) {
if (data.startsWith("User-Agent")) {
userAgentHeader = data.split(":")[1].trim();
break;
}
}
switch (requestType) {
case "GET": {
sendGetRequest(urlToCall, userAgentHeader);
break;
}
case "POST": {
String postParams = null;
//Get Form Data
if (!userDataArray[userDataArray.length - 1].isEmpty()) {
postParams = userDataArray[userDataArray.length - 1];
}
sendPostRequest(urlToCall, userAgentHeader, postParams);
break;
}
}
} else {
clientInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendPostRequest(String urlToCall, String userAgentHeader, String postParams) throws IOException {
URL urlToWriteAndReadFrom = new URL(urlToCall);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlToWriteAndReadFrom.openConnection();
httpURLConnection.setRequestMethod("POST");
// set User-Agent header
httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);
httpURLConnection.setDoOutput(true);
OutputStream urlOutputStream = httpURLConnection.getOutputStream();
if (postParams != null) {
urlOutputStream.write(postParams.getBytes());
urlOutputStream.flush();
}
urlOutputStream.close();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream dataReader = httpURLConnection.getInputStream();
//begin send response to client
byte inputInBytes[] = new byte[BUFFER_SIZE];
assert dataReader != null;
int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
while (index != -1) {
clientOutputStream.write(inputInBytes, 0, index);
index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
}
clientOutputStream.flush();
}
}
private void sendGetRequest(String urlToCall, String userAgentHeader) throws IOException {
URL urlToReadFrom = new URL(urlToCall);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlToReadFrom.openConnection();
// set True since reading and getting input
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
// set User-Agent header
httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream dataReader = httpURLConnection.getInputStream();
//begin send response to client
byte inputInBytes[] = new byte[BUFFER_SIZE];
assert dataReader != null;
int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
while (index != -1) {
clientOutputStream.write(inputInBytes, 0, index);
index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
}
clientOutputStream.flush();
}
}
}
PS。我对所有这些都是新手,所以如果我的代码中有任何错误,请指出它们
这里有一个完整的示例,说明如何创建一个 Java HTTP 服务器来处理 POST 和 GET 请求。
https://www.codeproject.com/Tips/1040097/Create-a-Simple-Web-Server-in-Java-HTTP-Server
这是共享的,这是非常原始的,如果不是像 Apache Tomcat 这样使用 J2EE Servlet 的服务器,我建议使用任何第三方库或轻量级 Java 服务器 Grizzly or Jetty为此目的而制作。
如何从 POST 请求中提取表单数据,例如。 $ curl -X POST -d asdf=blah http://localhost:8000/proxy/http://httpbin.org/post - 我需要提取 asdf=blah.
我目前的做法在很大程度上依赖于我阅读的特定格式的数据(我假设表单数据始终位于最后一行)。是否有更好的(and/or 更简单)的方式来获取不依赖于所读取数据格式的数据?
(注意:代理同时处理 GET 和 POST 请求)
这是我写的代码:
public class ProxyThread3 extends Thread {
private Socket clientSocket = null;
private OutputStream clientOutputStream;
private static final int BUFFER_SIZE = 32768;
public ProxyThread3(Socket socket) {
super("ProxyThread");
this.clientSocket = socket;
}
public void run() {
try {
clientOutputStream = clientSocket.getOutputStream();
// Read request
InputStream clientInputStream = clientSocket.getInputStream();
byte[] b = new byte[8196];
int len = clientInputStream.read(b);
String urlToCall = "";
if (len > 0) {
String userData = new String(b, 0, len);
String[] userDataArray = userData.split("\n");
//Parse first line to get URL
String firstLine = userDataArray[0];
for (int i = 0; i < firstLine.length(); i++) {
if (firstLine.substring(i).startsWith("http://")) {
urlToCall = firstLine.substring(i).split(" ")[0];
break;
}
}
//get request type
String requestType = firstLine.split(" ")[0];
String userAgentHeader = "";
//get USER-AGENT Header and Accept Header
for (String data : userDataArray) {
if (data.startsWith("User-Agent")) {
userAgentHeader = data.split(":")[1].trim();
break;
}
}
switch (requestType) {
case "GET": {
sendGetRequest(urlToCall, userAgentHeader);
break;
}
case "POST": {
String postParams = null;
//Get Form Data
if (!userDataArray[userDataArray.length - 1].isEmpty()) {
postParams = userDataArray[userDataArray.length - 1];
}
sendPostRequest(urlToCall, userAgentHeader, postParams);
break;
}
}
} else {
clientInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendPostRequest(String urlToCall, String userAgentHeader, String postParams) throws IOException {
URL urlToWriteAndReadFrom = new URL(urlToCall);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlToWriteAndReadFrom.openConnection();
httpURLConnection.setRequestMethod("POST");
// set User-Agent header
httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);
httpURLConnection.setDoOutput(true);
OutputStream urlOutputStream = httpURLConnection.getOutputStream();
if (postParams != null) {
urlOutputStream.write(postParams.getBytes());
urlOutputStream.flush();
}
urlOutputStream.close();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream dataReader = httpURLConnection.getInputStream();
//begin send response to client
byte inputInBytes[] = new byte[BUFFER_SIZE];
assert dataReader != null;
int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
while (index != -1) {
clientOutputStream.write(inputInBytes, 0, index);
index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
}
clientOutputStream.flush();
}
}
private void sendGetRequest(String urlToCall, String userAgentHeader) throws IOException {
URL urlToReadFrom = new URL(urlToCall);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlToReadFrom.openConnection();
// set True since reading and getting input
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
// set User-Agent header
httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream dataReader = httpURLConnection.getInputStream();
//begin send response to client
byte inputInBytes[] = new byte[BUFFER_SIZE];
assert dataReader != null;
int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
while (index != -1) {
clientOutputStream.write(inputInBytes, 0, index);
index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
}
clientOutputStream.flush();
}
}
}
PS。我对所有这些都是新手,所以如果我的代码中有任何错误,请指出它们
这里有一个完整的示例,说明如何创建一个 Java HTTP 服务器来处理 POST 和 GET 请求。
https://www.codeproject.com/Tips/1040097/Create-a-Simple-Web-Server-in-Java-HTTP-Server
这是共享的,这是非常原始的,如果不是像 Apache Tomcat 这样使用 J2EE Servlet 的服务器,我建议使用任何第三方库或轻量级 Java 服务器 Grizzly or Jetty为此目的而制作。