Http请求工具类

Http请求工具类

1、HTTP请求工具类代码

package test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.Charset;

public class HttpClient {
	
    private static final Log LOG = LogFactory.getLog(HttpClient.class);
    
    /** 
     * 发送 get请求 返回Json
     */  
    public static String getJson(String url,String token) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String responseMessange = "";
        try {
            HttpGet httpget = new HttpGet(uri);
            if(!"".equals(token))
                httpget.setHeader("x-wlk-Authorization",token);

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                	responseMessange = EntityUtils.toString(entity);
                }
            } finally {  
                response.close();  
            }  
        } catch (Exception e) {
            LOG.error("get请求失败",e);
        } finally {  
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {
                LOG.error("关闭连接失败",e);
            }  
        }  
        return responseMessange;
    }
    
    /** 
     * 发送post请求 返回Json
     */ 
    public String postJson(String url,String token,String body){
    	HttpPost post = null;
    	String responseMessange = "";
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            post = new HttpPost(url);
            // 构造消息头
            post.setHeader("Content-type",
                           "application/x-www.form-urlencoded; 
                           charset=utf-8");
            post.setHeader("Connection", "keep-alive");
            if(!"".equals(token))
                post.setHeader("x-wlk-Authorization",token);
            // 构建消息实体
            StringEntity entity = new StringEntity(body, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/x-www.form-urlencoded");
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
            try {  
                // 获取响应实体    
                HttpEntity httpEntity = response.getEntity();
                if (entity != null) {
                	responseMessange = EntityUtils.toString(httpEntity);
                }
            } finally {  
                ((Closeable) response).close();  
            }  
        } catch (Exception e) {
            LOG.error("post请求失败",e);
        }finally{
            if(post != null){
                try {
                    post.releaseConnection();
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    LOG.error("关闭连接失败",e);
                }
            }
        }
        return responseMessange;
    }
}

2、请求url获取token示例:

//url是举得一个例子,具体地址以实际情况为主
String url="http://ip/api/getToken"+"user="+user+"password="+password;
String Response= HttpClient.getJson(url,"");
  if(Strings.isBlank(Response)){
	throw new Exception("获取Response:"+Response);
  }else {
	JSONObject ResponseJson = JSONObject.parseObject(Response);
	String data = ResponseJson.getString("data");
	if(StringUtils.isBlank(data))
		throw new Exception("获取Response失败:"+Response);
	JSONObject dataJson = JSONObject.parseObject(data);
       //具体参数名称以实际情况为主
	token = dataJson.getString("token");
  }

3、StringUtils工具包的依赖

<dependency>
	<groupId>commons-lang</groupId>
	<artifactId>commons-lang</artifactId>
	<version>2.6</version>
</dependency>
posted @   晴天阴天下雨天  阅读(193)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示