使用HttpURLConnection在Request body中发送数据

时间:2017-06-01 10:41:06

标签: java web-services httpurlconnection microservices spark-java

我正在使用HttpURLConnection向使用JAVA Spark创建的本地部署的本地服务发出POST请求。当我使用HttpURLConnection进行POST调用时,我想在请求正文中发送一些数据但每次JAVA Spark中的请求体都为null 。以下是我正在使用的代码

Java Spark POST服务处理程序

post("/", (req, res) -> { System.out.println("Request Body: " + req.body()); return "Hello!!!!"; });

HTTPClass进行发布呼叫

`public class HTTPClassExample{
   public static void main(String[] args) {
        try{
            URL url = new URL("http://localhost:4567/");
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setRequestMethod("POST");
            httpCon.connect();
            OutputStream os = httpCon.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");    
            osw.write("Just Some Text");
            System.out.println(httpCon.getResponseCode());
            System.out.println(httpCon.getResponseMessage());
            osw.flush();
            osw.close();  
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}`

2 个答案:

答案 0 :(得分:12)

只有在将参数写入正文后才能调用httpCon.connect();,而不是之前。您的代码应如下所示:

URL url = new URL("http://localhost:4567/");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");    
osw.write("Just Some Text");
osw.flush();
osw.close();
os.close();  //don't forget to close the OutputStream
httpCon.connect();

//read the inputstream and print it
String result;
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result2 = bis.read();
while(result2 != -1) {
    buf.write((byte) result2);
    result2 = bis.read();
}
result = buf.toString();
System.out.println(result);

答案 1 :(得分:3)

我发布了XML格式的请求数据,代码如下所示。您还应该添加请求属性Accept和Content-Type。

URL url = new URL("....");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Accept", "application/xml");
httpConnection.setRequestProperty("Content-Type", "application/xml");

httpConnection.setDoOutput(true);
OutputStream outStream = httpConnection.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write(requestedXml);
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();

System.out.println(httpConnection.getResponseCode());
System.out.println(httpConnection.getResponseMessage());

InputStream xml = httpConnection.getInputStream();