zoukankan      html  css  js  c++  java
  • ahttpClient

    public static void main(String[] args) throws IOException {
            //1.打开浏览器
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //2.声明get请求
            HttpGet httpGet = new HttpGet("http://www.baidu.com/");
            //3.发送请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            //4.判断状态码
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                //通过EntityUtils工具类转成字符串
                String string = EntityUtils.toString(entity, "utf-8");
                System.out.println(string);
            }
            //5.关闭资源
            response.close();
            httpClient.close();
        }


    public String send(String postUrl,String json,String sign,String token) {
    String params = JSON.toJSONString(json);
    System.out.println(params);
    String url = postUrl;
    HttpClient httpClient = null;
    HttpPost postMethod = null;
    HttpResponse response = null;
    try {
    httpClient = HttpClients.createDefault();
    postMethod = new HttpPost(url);//传入URL地址
    //设置请求头
    postMethod.addHeader("Content-type", "application/json");
    postMethod.addHeader("sign", sign);//设置请求头
    postMethod.addHeader("token",token);
    //传入请求参数
    postMethod.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
    response = httpClient.execute(postMethod);//获取响应
    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println("HTTP Status Code:" + statusCode);
    if (statusCode != HttpStatus.SC_OK) {
    System.out.println("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
    }
    HttpEntity httpEntity = response.getEntity();
    String reponseContent = EntityUtils.toString(httpEntity);
    EntityUtils.consume(httpEntity);//释放资源
    System.out.println("响应内容:" + reponseContent);
    return reponseContent;
    } catch (Exception e) {
    e.printStackTrace();
    }
    return "";
    }
     
  • 相关阅读:
    How to run Java main class and pass application arguments in Maven?
    【转】三年后再反思我的" Java Web项目管理得失谈"
    Object.keys()
    angular $resource 的 get请求 和 post请求
    vue 自定义 移动端筛选条件
    获取当前时间 YYYY-MM-DD
    vue-router 二级路由
    blob 对象 实现分片上传 及 显示进度条
    js性能优化之函数节流(分流函数)
    vue + vue-lazyload 实现图片懒加载
  • 原文地址:https://www.cnblogs.com/otways/p/11561851.html
Copyright © 2011-2022 走看看