postUtil.java 2.4 KB
package com.bsth.utils;

import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

public class postUtil {
    
    public static String send(String url, JSONObject jsonObject, String encoding, String token) throws ParseException, IOException {
        String body = "";

        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);

        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader("Content-Type", "application/json"));

        httpPost.setEntity(s);
        System.out.println("请求地址:" + url);

        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("Access-Token", token);

        CloseableHttpResponse response = client.execute(httpPost);

        HttpEntity entity = response.getEntity();
        if (entity != null)
        {
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);

        response.close();
        return body;
    }

    public static String sendy(String url, String object, String encoding, String token) throws ParseException, IOException {
        String body = "";

        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);

        StringEntity s = new StringEntity(object, "utf-8");
        s.setContentEncoding(new BasicHeader("Content-Type", "application/json"));

        httpPost.setEntity(s);
        System.out.println("请求地址:" + url);

        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("Access-Token", token);

        CloseableHttpResponse response = client.execute(httpPost);

        HttpEntity entity = response.getEntity();
        if (entity != null)
        {
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);

        response.close();
        return body;
    }

}