Trae Moore
Trae Moore

Reputation: 1787

JAVA send/receive information via json

I've been researching on how to send and receive information to a url, via json for the last 3 days. I have found a lot of documentation and code examples on how to do it, I just can't comprehend what they're saying. I've imported god knows how many .jar files into my eclipse package. Does anyone have a good example on how to connect to a url, send/receive information (even login), parse it, and send more information? I understand that I'm asking for a lot. I don't need all the answers, good documentation and some good examples would make me soooo happy.

Upvotes: 1

Views: 1961

Answers (2)

plosco
plosco

Reputation: 901

Found a really solid example here on this blog http://www.gnovus.com/blog/programming/making-http-post-request-json-using-apaches-httpclient

Pasted below if for some reason the link doesnt work.

public class SimpleHTTPPOSTRequester {

private String apiusername;
private String apipassword;
private String apiURL;

public SimpleHTTPPOSTRequester(String apiusername, String apipassword, String apiURL) {        
    this.apiURL = apiURL;
    this.apiusername = apiusername;
    this.apipassword = apipassword;
}

public void makeHTTPPOSTRequest() {
    try {
        HttpClient c = new DefaultHttpClient();        
        HttpPost p = new HttpPost(this.apiURL);        

        p.setEntity(new StringEntity("{\"username\":\"" + this.apiusername + "\",\"password\":\"" + this.apipassword + "\"}", 
                         ContentType.create("application/json")));

        HttpResponse r = c.execute(p);

        BufferedReader rd = new BufferedReader(new InputStreamReader(r.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
           //Parse our JSON response               
           JSONParser j = new JSONParser();
           JSONObject o = (JSONObject)j.parse(line);
           Map response = (Map)o.get("response");

           System.out.println(response.get("somevalue"));
        }
    }
    catch(ParseException e) {
        System.out.println(e);
    }
    catch(IOException e) {
        System.out.println(e);
    }                        
}    
}

Upvotes: 0

Rick Mangi
Rick Mangi

Reputation: 3769

Start with http://hc.apache.org/ Then look at http://code.google.com/p/google-gson/ or: http://wiki.fasterxml.com/JacksonHome

That should be all you need.

Upvotes: 3

Related Questions