Mocanu Bogdan
Mocanu Bogdan

Reputation: 36

Access REST API in Java with json parameters

I do not know what I am doing wrong, but I cannot access a REST API using the POST method in Java with Json parameters.

Each time I run the program, I receive Java.net.SocketException - Connection Reset.

I tried to access the API from PHP, and it worked.

Code: https://github.com/BobTheProgrammer/Question/blob/master/POST

Upvotes: 0

Views: 934

Answers (2)

Valamburi M
Valamburi M

Reputation: 702

There is a problem with the JSON syntax in your source code in line number 55, you have missed a comma after the user object.

Replace this line

String urlParameters = "{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"}\"method\":\"user\",\"website\":\"http://website.net/\"}}";

with this one(added a comma after the user object before method)

String urlParameters = "{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"},\"method\":\"user\",\"website\":\"http://website.net/\"}}";

Upvotes: 1

Abdul Manaf
Abdul Manaf

Reputation: 4993

try this one

    public static void HttpPost() {
    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "https://api.website.net/auth/token");
        StringEntity input = new StringEntity("{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"}\"method\":\"user\",\"website\":\"http://website.net/\"}}");
        post.setEntity(input);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

Upvotes: 1

Related Questions