apache.http
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
- 发送post请求
- "content-type", "application/json"
public static String exec(String serverUrl, String cmd) {
CloseableHttpResponse response = null;
try {
cmd = cmd.replace("\"", "\\\"");
// param
StringEntity entity = new StringEntity(String.format("{\"gremlin\":\"%s\"}", cmd), "UTF-8");
// send request
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(serverUrl);
post.setHeader("content-type", "application/json");
post.setEntity(entity);
String req = EntityUtils.toString(entity);
log.info("req=" + req);
// get response
response = httpclient.execute(post);
String ret = EntityUtils.toString(response.getEntity());
log.info("ret=" + ret);
return ret;
} catch (Exception e) {
log.error("", e);
return null;
} finally {
try {
response.close();
} catch (IOException e) {
log.error("", e);
}
}
}
okhttp
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.0</version>
</dependency>
public class HttpClientUtils {
public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
private static OkHttpClient client = new OkHttpClient();
public static String access(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}