Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    static String url = "http://api.godex.io:8080/api/";
    static String charset = "UTF-8";
    static int statusCode = 200;

    public static JSONObject postRequest(String query) {

        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(url + query).openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept-Charset", charset);

            statusCode = connection.getResponseCode();
            if (statusCode != 200) {
                return null;
            }

            InputStream response = connection.getInputStream();
            BufferedReader bR = new BufferedReader(new InputStreamReader(response));
            String line = "";

            StringBuilder responseStrBuilder = new StringBuilder();
            while ((line = bR.readLine()) != null) {
                responseStrBuilder.append(line);
            }
            response.close();

            return new JSONObject(responseStrBuilder.toString());

        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return new JSONObject();
    }
}