Home > Blockchain >  On which IP to host an http server? (Heroku, no frameworks)
On which IP to host an http server? (Heroku, no frameworks)

Time:12-14

On which IP can I host my http server (pure java) on heroku? Will the IP of the application that Heroku provides for web applications be suitable? If yes, then help me set up Procfile if needed.

My Procfile: worker: java -jar (name of jar file).jar

My 1-class code:

package discord.wosaj;

import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static java.util.stream.Collectors.*;

public class Main {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress("https://rests-server.herokuapp.com", 80), 0);
        server.createContext("/api/hello", httpExchange -> {
            if(httpExchange.getRequestMethod().equals("GET")) {
                String out = "<head><meta charset=\"UTF-8\"></head>\n"  
                        "<h1>Params:</h1>"  
                        Main.splitQuery(httpExchange.getRequestURI().getRawQuery());
                httpExchange.sendResponseHeaders(200, out.getBytes().length);
                OutputStream stream = httpExchange.getResponseBody();
                stream.write(out.getBytes());
                stream.flush();
                stream.close();
            } else {
                httpExchange.sendResponseHeaders(405, -1);
            }
        });
        server.setExecutor(null);
        server.start();
    }

    public static Map<String, List<String>> splitQuery(String query) {
        if (query == null || "".equals(query)) {
            return Collections.emptyMap();
        }

        return Pattern.compile("&").splitAsStream(query)
                .map(s -> Arrays.copyOf(s.split("="), 2))
                .collect(groupingBy(s -> decode(s[0]), mapping(s -> decode(s[1]), toList())));
    }

    private static String decode(final String encoded) {
        try {
            return encoded == null ? null : URLDecoder.decode(encoded, "UTF-8");
        } catch (final UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 is a required encoding", e);
        }
    }
}

I tried 0.0.0.0, it starts, but it is unclear to which address to make requests

the port is determined by the environment variable "PORT"

CodePudding user response:

A solution has been found, but I will still write: Set the ip to 0.0.0.0 and the port to the PORT environment variable, set it as web in the procfile, it should work

  • Related