1,创建一个Helidon MP项目
mvn archetype:generate -DinteractiveMode=false \
-DarchetypeGroupId=io.helidon.archetypes \
-DarchetypeArtifactId=helidon-quickstart-mp \
-DarchetypeVersion=1.0.0 \
-DgroupId=io.helidon.guides \
-DartifactId=mp-restful-webservice \
-Dpackage=io.helidon.guides.mp.restfulwebservice
2,修改pom.xml,在<dependencies>标签里追加unirest-java依赖
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
3,更新maven,取得unirest-java jar包。使用Eclipse工具时,在项目上点击右键,然后依次点击[Maven]->[Update Project],最后点击[OK]按钮。
4,修改src/main/resources/META-INF/microprofile-config.properties,最近rest api访问的url和api key。请事先在openweathermap.org网站上注册并获得api key。
app.api.baseUrl=https://api.openweathermap.org/data/2.5
app.api.key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
5,新建QuoteApplication.java类。
package io.helidon.guides.mp.restfulwebservice;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationScoped
@ApplicationPath("/")
public class QuoteApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> set = new HashSet<>();
set.add(QuoteResource.class);
return Collections.unmodifiableSet(set);
}
}
6,新建QuoteResource.java类。
package io.helidon.guides.mp.restfulwebservice;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
@Path("/quote")
@RequestScoped
public class QuoteResource {
private static String apiBaseUrl = null;
private static String apiKey = null;
@Inject
public QuoteResource(@ConfigProperty(name = "app.api.baseUrl") final String apiBaseUrl,
@ConfigProperty(name = "app.api.key") final String apiKey) {
if (this.apiBaseUrl == null) {
this.apiBaseUrl = apiBaseUrl;
}
if (this.apiKey == null) {
this.apiKey = apiKey;
}
}
@SuppressWarnings("checkstyle:designforextension")
@Path("/random")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getRandomQuote() throws UnirestException {
String url = apiBaseUrl + "/weather?q=London&appid=" + apiKey;
HttpResponse<JsonNode> quote = Unirest.get(url).asJson();
return quote.getBody().toString();
}
}
7,运行项目,右键点击Main.java并运行。日志如下
2019.03.14 10:34:01 INFO org.jboss.weld.Version Thread[main,5,main]: WELD-000900: 3.0.3 (Final)
2019.03.14 10:34:01 INFO org.jboss.weld.Bootstrap Thread[main,5,main]: WELD-ENV-000020: Using jandex for bean discovery
2019.03.14 10:34:02 INFO org.jboss.weld.Bootstrap Thread[main,5,main]: WELD-000101: Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
2019.03.14 10:34:02 INFO org.jboss.weld.Event Thread[main,5,main]: WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider.processAnnotatedType(@Observes ProcessAnnotatedType) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds.
2019.03.14 10:34:02 WARN org.jboss.weld.Bootstrap Thread[main,5,main]: WELD-000146: BeforeBeanDiscovery.addAnnotatedType(AnnotatedType<?>) used for class org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider$JaxRsParamProducer is deprecated from CDI 1.1!
2019.03.14 10:34:04 INFO org.jboss.weld.Bootstrap Thread[main,5,main]: WELD-ENV-002003: Weld SE container bd1d650f-592e-400a-a2ff-b168e1f05b35 initialized
2019.03.14 10:34:04 INFO io.helidon.microprofile.security.SecurityMpService Thread[main,5,main]: Security extension for microprofile is enabled, yet security configuration is missing from config (requires providers configuration at key security.providers). Security will not have any valid provider.
2019.03.14 10:34:05 INFO io.helidon.webserver.NettyWebServer Thread[nioEventLoopGroup-2-1,10,main]: Channel '@default' started: [id: 0x9f97ffc3, L:/0:0:0:0:0:0:0:0:8080]
2019.03.14 10:34:05 INFO io.helidon.microprofile.server.ServerImpl Thread[nioEventLoopGroup-2-1,10,main]: Server started on http://localhost:8080 (and all other host addresses) in 134 milliseconds.
http://localhost:8080/greet
8,访问
curl http://localhost:8080/quote/random
结果
{"dt":1552530790,"coord":{"lon":-0.13,"lat":51.51},"visibility":10000,"weather":[{"icon":"10n","description":"light rain","main":"Rain","id":500}],"name":"London","cod":200,"main":{"temp":280.69,"temp_min":279.82,"humidity":81,"pressure":1010,"temp_max":281.48},"clouds":{"all":92},"id":2643743,"sys":{"country":"GB","sunrise":1552544248,"sunset":1552586578,"id":1502,"type":1,"message":0.0169},"base":"stations","wind":{"deg":250,"speed":6.7}}
结尾!