jeudi 30 juin 2016

How do you perform a HTTP POST in Java?

Recently I have been using an app on Chrome called Postman to perform HTTP POSTs for my convenience, but now I want to try doing this via Java instead because I want to make a program that sends various HTTP POSTs to a server and read/stores the response it returns to me.

In my Java code, I have this so far

import java.net.*;
import java.io.*;

class A {
    //A Java program to post and receive response
    public static void main(String[] args) throws Exception {

        String site = "http://username:password@192.168.0.10/data/info";

        URL url = new URL(site);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        String Body = "<Command><Name>Get_First_Name</Name></Command>"

        // How would I send this properly and read the response?

        System.out.print("The End");
    }
}

I have done some standard google searches, but I couldn't follow most of the answers since apparently there are multiple ways to do this and I never found a concrete method in the end. I believe I got the connection set up correct, but all that I couldn't digest into my brain was how to actually do the POST itself. It would be awesome if someone can guide me in the right direction with this.

REFERENCE: Here is a crop of Postman and what I put into it for my POSTs which is what I am now trying to do in Java because I don't want to rely on this app for the rest of my HTTP POSTs in the future.

enter image description here

Aucun commentaire:

Enregistrer un commentaire