httpclient获取url响应信息Demo
发布日期:2021-05-15 07:14:19 浏览次数:14 分类:精选文章

本文共 4596 字,大约阅读时间需要 15 分钟。

httpclient获取url响应信息Demo,两种方式:

pom.xml

4.0.0
dtwave_pro
com.dtwave.pros
1.0-SNAPSHOT
org.apache.httpcomponents
httpclient
4.5.3
com.alibaba
fastjson
1.2.24
org.apache.commons
commons-lang3
3.8.1
org.apache.commons
commons-io
1.3.2
org.apache.hive
hive-exec
1.2.1
provided
junit
junit
3.8.1
test
maven-clean-plugin
3.0.0
maven-resources-plugin
3.0.2
maven-compiler-plugin
3.7.0
maven-surefire-plugin
2.20.1
maven-jar-plugin
3.0.2
maven-install-plugin
2.5.2
maven-deploy-plugin
2.8.2
maven-assembly-plugin
jar-with-dependencies
make-assembly
package
single

get和post请求:

package com.dtwave.duruo;import org.apache.commons.io.IOUtils;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import java.io.IOException;import java.io.InputStream;public class HttpClientDemo {    public static void main(String[] args) {        System.out.println(doGetMethod("http://www.baidu.com"));        System.out.println(doPostMethod("http://www.baidu.com"));    }    // get请求    public static String doGetMethod(String url){        // 获取httpclient对象        CloseableHttpClient httpclient = HttpClients.createDefault();        // 创建GET请求        // String url = "http://www.baidu.com";        HttpGet hg = new HttpGet(url);        // 设置参数        hg.addHeader("Content-Type", "text/html;charset=utf-8");        String result = null;        try {            CloseableHttpResponse response = httpclient.execute(hg);            InputStream in = response.getEntity().getContent();            result = IOUtils.toString(in);            // 关闭流            in.close();            response.close();        } catch (Exception e) {            e.printStackTrace();        }        return result ;    }    // post请求方法    public static String doPostMethod(String url){        String res = null;        // 获取httpclient对象        CloseableHttpClient httpclient = HttpClients.createDefault();        // 创建POST请求        // String url = "http://www.baidu.com";        HttpPost hp = new HttpPost(url);        hp.addHeader("Content-Type", "text/html;charset=utf-8");        //        try {            CloseableHttpResponse chr = httpclient.execute(hp);            InputStream in = chr.getEntity().getContent();            res = IOUtils.toString(in);        } catch (Exception e) {            e.printStackTrace();        }        return res;    }}

 

上一篇:elasticsearch安装启动的那些坑
下一篇:maven 中的 scope含义的说明

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月06日 06时50分20秒