我是 Java 新手,应该将 XML 文件发送到 HTTP 服务器。应首先将 XML 文件转换为字符串:
我从服务器收到错误:
[stdout] (http--127.0.0.1-8080-1) failed in postjava.lang.NullPointerException
[stdout] (http--127.0.0.1-8080-1) received post request :
似乎我没有向服务器发送任何内容。
这是代码
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
public class try_post {
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("D:\\n.xml");
StringWriter stringWriter = new StringWriter();
Transformer transformer =TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
String strFileContent = stringWriter.toString();
System.out.println(strFileContent);
System.out.println( strFileContent.getClass().getName());
System.out.println("xml file converted to string");
String param="param1=" + URLEncoder.encode(strFileContent ,"UTF-8");
URL url = new URL("http://localhost:8080/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
// connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(param.getBytes().length);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(param);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
String response= "";
StreamSource source = new StreamSource(fileReader);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);*/
DataOutputStream fos = new DataOutputStream(connection.getOutputStream ());
System.out.println("Response code: " + connection.getResponseCode());
connection.disconnect();}
catch (MalformedURLException ex) {
System.out.print("MalformedURLException");
} catch (Exception ex) {
System.out.print(" Exception: "+ex.getMessage());
}
}
}