发送HTTP请求

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>
  • 发送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();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,188评论 19 139
  • 大家好,我是IT修真院深圳分院第01期学员,一枚正直纯洁善良的web程序员。今天给大家分享一下,修真院官网JAVA...
    老菜菜阅读 28,050评论 0 3
  • 简单介绍 HTTP 的全称是Hypertext Transfer Protocol Vertion (超文本传输协...
    屋檐下的燕雀阅读 8,800评论 0 2
  • 一、 生成HTTP请求消息 1.1 各种各样的URL浏览器是一个具备多种客户端功能的综合性客户端软件,会根据UR...
    gioxx2阅读 11,540评论 1 8
  • 写在3月21日 清晨收到一条祝福:祝“世界睡眠日”好梦。对方或许不知,我在所谓的睡眠日,刚完成了又一次的“今夜无眠...
    我是Cola阅读 2,784评论 0 0

友情链接更多精彩内容