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 "";
    }
     
  • 相关阅读:
    CSS学习笔记之(1):文档流、块级元素、内联元素
    java nio纯理论
    CSS权重计算
    JS闭包(转载)
    [Journal]我是如何DIY博客的
    [CodeForces]Codeforces Round #428 (Div. 2)
    [Data Structure][线段树]BZOJ3211 花神游历各国
    [Journal]有一种感动叫ACM——记WJMZBMR在成都赛区开幕式上的讲话
    美团面试失败(Java开发)
    继承的初始化过程
  • 原文地址:https://www.cnblogs.com/otways/p/11561851.html
Copyright © 2011-2022 走看看