我正在尝试构建一个JAVA应用程序(在端口9090上运行),该应用程序从HTTP POST接收JSON文件并将其转换为XML并将其发送到另一个应用程序(APP2),该应用程序在不同的端口运行并进一步处理已经完成了。
我已经实现了所有代码接受从HTTP POST接收JSON的代码,因为我不知道如何开始实现它。
任何资源/链接都会非常有用。
P.S。不要问我为什么要以复杂的方式完成这项工作,这正是我公司所期望的。
为APP2实施以下代码。
服务器端:
public class ServerSide{
static String JsonPath = "src/TestApp.json";
static String XMLPath = "TestApp";
static String Port = "Port1";
public static void main(String[] args) throws IOException, SAXException {
// if (args.length != 1) {
// System.err.println(
// "No argument specified");
// System.exit(1);
// }
ConfigReader reader = new ConfigReader();
int port = Integer.parseInt(reader.getPropValues("Port1"));
System.out.println(port);
//JSON to XML conversion
try {
JsonToXML.JsonConversion(JsonPath,XMLPath);
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ServerSocket ssock = new ServerSocket(port);
Socket socket = ssock.accept();
System.out.println("Server Started");
//The InetAddress specification
InetAddress IA = InetAddress.getByName("localhost");
//Specify the file
System.out.println("This is the connection ");
File file = new File("Sahil.xml");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
//Get socket's output stream
OutputStream os = socket.getOutputStream();
//Read File Contents into contents array
byte[] contents;
long fileLength = file.length();
System.out.println(" This is file length "+ fileLength);
long current = 0;
long start = System.nanoTime();
while(current!=fileLength){
int size = 10000;
if(fileLength - current >= size){
System.out.println(" This is the file length "+fileLength+" current : "+current+"size : "+size);
current += size;
}
else{
size = (int)(fileLength - current);
current = fileLength;
System.out.println(" This is the current "+current);
}
contents = new byte[size];
bis.read(contents, 0, size);
os.write(contents);
System.out.println("Sending file ... "+(current*100)/fileLength+"% complete!");
}
os.flush();
//File transfer done. Close the socket connection!
socket.close();
ssock.close();
System.out.println("File sent succesfully!");
}
}
客户端:
public class ClientSide{
public static void main(String[] args) throws Exception{
String line;
//Initialize socket
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket(host.getHostName(), 4355);
byte[] contents = new byte[10000];
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//No of bytes read in one read() call
while ((line = br.readLine()) != null){
System.out.println(line);
}
socket.close();
System.out.println("File saved successfully!");
}
}
关于如何实现HTTP POST以将文件发送到APP1的问题,APP1在不同的端口运行,然后将其发送到APP2。
答案 0 :(得分:0)
我不确定如何从HTTP POST接收文件
我想你有一些带有文件输入类型和正确的enctype
的html表单... enctype="multipart/form-data"> <input type="file" id="input">
稍后在POST方法处理程序中,您必须从请求中提取该文件
Part filePart = request.getPart("file");
我建议的唯一不要手动进行文件提取。显然使用一些现成的库