-
-
Save spolti/bac0f153ad53bd0e96985f5b17e7c93b to your computer and use it in GitHub Desktop.
GreetingResource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.URI; | |
import java.nio.charset.StandardCharsets; | |
import java.util.concurrent.TimeUnit; | |
import javax.ws.rs.GET; | |
import javax.ws.rs.Path; | |
import javax.ws.rs.Produces; | |
import javax.ws.rs.core.MediaType; | |
import javax.ws.rs.core.Response; | |
import okhttp3.OkHttpClient; | |
import okhttp3.Request; | |
import okhttp3.RequestBody; | |
import org.eclipse.microprofile.config.inject.ConfigProperty; | |
@Path("/hello") | |
public class GreetingResource { | |
@ConfigProperty(name = "my.knative.service") | |
URI service; | |
@GET | |
@Produces(MediaType.APPLICATION_JSON) | |
public Response hello() { | |
return Response.accepted(doPost(service)).status(javax.ws.rs.core.Response.Status.OK).build(); | |
} | |
private String doPost(URI uri) { | |
if (null == uri) { | |
throw new RuntimeException("URI is null"); | |
} | |
OkHttpClient okClient = new OkHttpClient.Builder() | |
.connectTimeout(15, TimeUnit.SECONDS) | |
.writeTimeout(15, TimeUnit.SECONDS) | |
.readTimeout(60, TimeUnit.SECONDS) | |
.build(); | |
StringBuilder url = new StringBuilder(uri.getScheme()) | |
.append("://") | |
.append(uri.getHost()); | |
if (uri.getPort() != -1) { | |
url.append(":"); | |
url.append(uri.getPort()); | |
} | |
String payload = "{\"workflowdata\" : {\"name\": \"John\", \"language\": \"Spanish\"}}"; | |
url.append("/jsongreet"); | |
System.out.println("Calling url -- " + url + " with payload -> " + payload); | |
Request request = new Request.Builder() | |
.url(url.toString()) | |
.addHeader("charset", StandardCharsets.UTF_8.name()) | |
.post(RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), payload)) | |
.build(); | |
try (okhttp3.Response response = okClient.newCall(request).execute()) { | |
return response.body().string(); | |
} catch (final Exception e) { | |
e.printStackTrace(); | |
} | |
return "no response body to return"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment