Java 服务器http请求工具

package utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {

    public static JSONObject get(String url){

        HttpURLConnection http = null;
        InputStream is = null;
        try {
            URL urlGet = new URL(url);
            http = (HttpURLConnection) urlGet.openConnection();

            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");

            http.connect();

            is =http.getInputStream();
            int size =is.available();
            byte[] jsonBytes =new byte[size];
            is.read(jsonBytes);
            String message=new String(jsonBytes,"UTF-8");
            return JSONObject.parseObject(message);
        } catch (Exception e) {
            return null;
        }finally {
            if(null != http) http.disconnect();
            try {
                if (null != is) is.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }

    public static JSONObject doPost(String url, String params) throws Exception {
        Request request = Request.Post(url);

        if (params != null)
            request.bodyByteArray(params.getBytes("UTF8"));

        Response response = request.execute();
        String jsonData = response.returnContent().asString();
        JSONObject json = JSONObject.parseObject(jsonData);
        return json;
    }

    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.parseObject(jsonData);
        return json;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值