org.apache.http 工具类使用

本贴最后更新于 1818 天前,其中的信息可能已经时移世改

Maven 的 pom 引入:

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.7</version>
</dependency>

依赖的 jar 文件:

jar 包依赖.png

GET 方法:

import org.apache.http.HttpEntity;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public static String get(String url) throws Exception{
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response2 = HttpClients.createDefault().execute(httpGet);

        try {

            response2.getStatusLine().getStatusCode();//HttpStatus.SC_OK

            HttpEntity entity2 = response2.getEntity();
            String response=EntityUtils.toString(entity2,"utf-8");//返回报文

            EntityUtils.consume(entity2);//关闭资源
            return response;
        } finally {
            response2.close();//关闭资源
        }
    }

POST 方法访问 http:

import org.apache.http.HttpEntity;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public static String post(String url,String json) throws Exception{

        StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);//设置消息头 Content-Type application/json; charset=UTF-8
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        CloseableHttpResponse response2 = HttpClients.createDefault().execute(httpPost);

        try {

            response2.getStatusLine().getStatusCode();//HttpStatus.SC_OK

            HttpEntity entity2 = response2.getEntity();
            String response=EntityUtils.toString(entity2,"utf-8");//返回报文

            EntityUtils.consume(entity2);//关闭资源
            return response;
        } finally {
            response2.close();//关闭资源
        }
    }

POST 方法访问 https:

去除 ssl 验证

                
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3187 引用 • 8213 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...