How do you send data in a Request body using HttpURLConnection?

后端 未结 2 1886
误落风尘
误落风尘 2020-12-30 03:24

I am using HttpURLConnection to make a POST request to a local service deployed locally and created using JAVA Spark. I want to send some data in reques

相关标签:
2条回答
  • 2020-12-30 04:22

    I posted with the requested data in XML format and the code look like this. You should add the request property Accept and Content-Type also.

    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();
    
    0 讨论(0)
  • 2020-12-30 04:24

    You should call httpCon.connect(); only after you write your parameters in the body and not before. Your code should look like this:

    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(httpCon.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);
    
    0 讨论(0)
提交回复
热议问题