JAVA HTTP请求工具类

JAVA新手,在项目中应用到的工具,进行简单的总结,随便写写,有不对希望大神指正,谢谢....

在开发项目中, 如果需要进行跨域请求,都会涉及到在代码中实现HTTP的请求访问.

(百度过许多次都没有发现比较简单的方法,所以就简单整理一下)

这里以Maven项目为例进行讲解:

    除其他配置外还需要Maven包:

   

<!-- 发送HTTP请求 -->
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/fluent-hc -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>fluent-hc</artifactId>
    <version>4.5.3</version>
</dependency>

<!-- net.sf.json.JSONObject 相关jsOn转化 -->
<dependency>    
    <groupId>net.sf.json-lib</groupId>    
    <artifactId>json-lib</artifactId>    
    <version>2.4</version>    
    <classifier>jdk15</classifier>    
</dependency> 

请求工具代码如下:

package com.wx.tool;


import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;

import net.sf.json.JSONObject;


public class HttpUtil {

    /**
     * <p>方法说明: HTTP POST 请求
     * <p>编码格式: UTF8
     * <p>参数说明: String urL 请求的路径
     * <p>参数说明: String parAms 请求的参数
     * <p>返回说明: JSONObject
     * */
    public static JSONObject doPost(String url, String params) throws Exception {
        Request request = Request.Post(url);
        request.bodyByteArray(params.getBytes("UTF8"));
        Response response = request.execute();
        String jsonData = response.returnContent().asString();
        
        /* 转化为 JSONObject 数据 */
        JSONObject json = JSONObject.fromObject(jsonData);
        return json;
    }
    
    /**
     * <p>方法说明: HTTP GET 请求
     * <p>编码格式: UTF8
     * <p>参数说明: String urL 请求的路径
     * <p>返回说明: JSONObject
     * */
    public static JSONObject doGet(String url) throws Exception{
        Request request = Request.Get(url);
        request.setHeader("Content-type", "application/json;charset=UTF8");
        Response response = request.execute();
        String jsonData = response.returnContent().asString();
        JSONObject json = JSONObject.fromObject(jsonData);
        return json;
    }
    
    /**
     * <p>方法说明: HTTP GET 请求
     * <p>编码格式: UTF8 , 微信编码转为UTF-8
     * <p>参数说明: String urL 请求的路径
     * <p>返回说明: JSONObject
     * */
    public static JSONObject doGetUTF8(String url) throws Exception {
        Request request = Request.Get(url);
        request.setHeader("Content-type", "application/json;charset=UTF8");
        Response response = request.execute();
        String jsonData = response.returnContent().asString();
        String string = new String(jsonData.getBytes("ISO-8859-1"),"UTF-8");
        JSONObject json = JSONObject.fromObject(string);
        return json;
    }
    
    
    /**
     * <p>方法说明: HTTP POST 请求
     * <p>编码格式: UTF8
     * <p>参数说明: String urL 请求的路径
     * <p>参数说明: String parAms 请求的参数
     * <p>返回说明: String
     * */
    public static String doPostToStr(String url, String params) throws Exception {
        Request request = Request.Post(url);
        request.bodyByteArray(params.getBytes("UTF8"));
        Response response = request.execute();
        return response.returnContent().asString();
    }
    
    /**
     * <p>方法说明: HTTP GET 请求
     * <p>编码格式: UTF8
     * <p>参数说明: String urL 请求的路径
     * <p>返回说明: String
     * */    
    public static String doGetToStr(String url) throws Exception {
        Request request = Request.Get(url);
        request.setHeader("Content-type", "application/json;charset=UTF8");
        Response response = request.execute();
        return response.returnContent().asString();
    }
    
}

上面是我封装的几个简单方法,这样就可以直接使用了:

package com.wx.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.tool.IsNull;
import com.wx.bean.AppPath;
import com.wx.tool.HttpUtil;

import net.sf.json.JSONObject;

/**
 * <p>类说明: 获取token线程
 * <p>创建人: geYang
 * <p>创建时间:2017.08.29
 * */
public class TokenThread implements Runnable {

    private static String access_token;
    
	private boolean close = false;         //线程控制

	/* 外界拿取access_token方法  */
    public static String getToken(){
        return access_token;
    }
	
	public void performClose() {
		this.close = true;
	}
	
    @Override
    public void run() {
	    while (!close){
		    try{
			    if( IsNull.isNull(access_token) ){
				    Thread.sleep(1000*3); 				//获取的access_token为空休眠3秒
			    }else{
				    Thread.sleep(7000*1000); 			//获取到access_token 休眠7000秒
			    }
			    access_token = getAccessToken();		//向服务器发起请求

			    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			    System.out.println(access_token);
				
		    }catch(Exception e){
				System.out.println("发生异常");
				e.printStackTrace();
                try{
                    Thread.sleep(1000*1); 				//发生异常休眠1秒
                }catch (Exception e1){
                	e.printStackTrace();
                	System.out.println("休眠发生异常");
                }
		    }
			
	    }
    }
	
	/**
	 * <p>方法说明: 获取access_token
	 * */
    private static String getAccessToken(){
	    try {
            /* 进行HTTP GET 请求 */
            JSONObject jsonObj = HttpUtil.doGet(AppPath.getUrl());
            String access_token = jsonObj.getString("access_token");
            
            return access_token;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("com.wx.tool.TokenThread.getAccessToken请求异常");
        }
        return null;
	}
    
	/**
	 * <p>方法说明:手动获取access_token
	 * */
	public static void main(String[] args) {
	    String access_token = getAccessToken();
	    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	    System.out.println(access_token);
	}
}

在 fluent-hc 包 中自动为我们处理了HTTP协议等相关高深问题.我们只需要传入路径和参数就可以使用GET和POST等请求,是不是非常简单.....

 

 

转载于:https://my.oschina.net/u/3681868/blog/1535818

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值