http请求调用demo

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;


public class HttpUtil {
    
    private static final Logger logger = Logger.getLogger(HttpUtil.class);
    
    public static String httpPost(String urlStr,JSONObject inParmMap) throws Exception{
        String resp= null;
        String query = JSONObject.toJSONString(inParmMap,SerializerFeature.WriteMapNullValue);
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr); 
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setConnectTimeout(120000);
            connection.setReadTimeout(120000);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/json");
            connection.connect();
            outputStream = connection.getOutputStream();
            outputStream.write(query.getBytes("UTF-8"));
            outputStream.flush();
           
            inputStreamReader = new InputStreamReader(connection.getInputStream());
            reader = new BufferedReader(inputStreamReader);
            String lines;
            StringBuffer sbf = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sbf.append(lines);
            }
           resp = sbf.toString();    
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e);
        }finally {
            if(null != outputStream) outputStream.close();
            if(null != inputStreamReader) inputStreamReader.close();
            if(null != reader) reader.close();
            if(null != connection) connection.disconnect();
        }
        return resp;
    }
    
}
 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值