发送HTTP请求

apache.http

  • HttpClient
           
                org.apache.httpcomponents
                httpclient
                4.5.3
            
  • 发送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

  • OkHttp
     
        com.squareup.okhttp3
        okhttp
        3.9.0
      
  • 发送get和post
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();
    }
}

你可能感兴趣的:(发送HTTP请求)