我开始学习常规。我喜欢使用httpbuilder。我发现我应该使用@Grab,所以我写了这个例子
// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
@Grapes(
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.5.7')
)
import org.apache.http.client.methods.*
import org.apache.http.entity.*
import org.apache.http.impl.client.*
import groovy.json.*
// build JSON
def map = [:]
map["name"] = "Maritime DevCon"
map["address"] = "Fredericton"
map["handle"] = "maritimedevcon"
def jsonBody = new JsonBuilder(map).toString()
// build HTTP POST
def url = 'http://jsonplaceholder.typicode.com/posts'
def post = new HttpPost(url)
post.addHeader("content-type", "application/json")
post.setEntity(new StringEntity(jsonBody))
// execute
def client = HttpClientBuilder.create().build()
def response = client.execute(post)
def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
def jsonResponse = bufferedReader.getText()
println "response: \n" + jsonResponse
def slurper = new JsonSlurper()
def resultMap = slurper.parseText(jsonResponse)
assert "Maritime DevCon" == resultMap["name"]
assert resultMap["id"] != null
我的互联网连接正常,但是我得到了
Information:Groovyc: While compiling groovyWItholdJava: java.lang.RuntimeException: Error grabbing Grapes -- [download failed: commons-logging#commons-logging;1.2!commons-logging.jar]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
...
这可能是什么原因?我什至可以在浏览器中打开mvn中央存储库。