使用HttpURLConnection调用HTTP示例

调用HTTP的方法有很多种,使用Java原生的HttpURLConnection可以,也可以使用HttpClient包

package util;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;

import java.util.regex.Pattern;

import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class APIHelper {
    private static Logger log =Logger.getLogger(APIHelper.class);
    private static Logger errorLog =Logger.getLogger("errorlog");
    public static void main(String[] args)
    {
        InputStream is = APIHelper.class.getClassLoader().getResourceAsStream("config/log4j.properties");
        
        PropertyConfigurator.configure(is);
        
       
        String url0 ="http://nkweb-uat.huawei.com/pm/services/dc/excel";//http://login-beta.huawei.com/login
        String method ="POST";
        Map<String,String> params =new HashMap<>();
       
        int[] responseCode =new int[1];
        params.put("paramName1", "paramValue1");
        params.put("paramName2", "paramValue2");
        String[] url ="http://localhost.huawei.com:8090/something";
        
        String res =request(url[i],method,params1,responseCode);
        System.out.println(responseCode[0]);
        System.out.println(res);
        
    }
    
    public static String getRequest(String address, Map<String,String> map, int[] responseCode)
    {
        log.info("Enter getRequest()");
        if(!map.isEmpty())
        {
            address +="?";
            for(Map.Entry<String, String> entry :map.entrySet())
            {
                if(!address.endsWith("?")) address +="&";
                address += entry.getKey()+"="+entry.getValue();
            }
        }
        System.out.println(address);
        return request(address,"GET",map,responseCode);
    }
    
    public static String request(String address, String method, Map<String,String> map, int[] responseCode)
    {
        log.info("Enter request()");
        StringBuffer response =null;
        responseCode[0] =404;
        if(!checkURL(address)) return null;
        BufferedReader br =null;
        HttpURLConnection con =null;
        try{
            URL url =new URL(address);
            con =(HttpURLConnection) url.openConnection();
            con.setConnectTimeout(3000);//超时时间3秒
            con.setRequestProperty("Accept-Language", "en-US;q=1");
            con.setRequestProperty("Content-Type", "application/json;utf-8");
            con.setRequestMethod(method);
            con.setDoOutput(true);
            DataOutputStream dos =new DataOutputStream(con.getOutputStream());
            //设置参数格式
            String data =setFormat(map);
            
            if(!data.trim().equals("")) dos.writeBytes(data);
            dos.flush();
            dos.close();
            responseCode[0] =con.getResponseCode();
            
            if(responseCode[0] <400)
            {
                br =new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
            }else{
                if(null!=con.getErrorStream())
                br =new BufferedReader(new InputStreamReader(con.getErrorStream(),"UTF-8"));
            }
            String inputLine;
            response =new StringBuffer();
            while(null!=br&&(inputLine =br.readLine())!=null)
            {
                response.append(inputLine);
                response.append("\n");
            }
            
            
        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            errorLog.error(address+":"+e);
            errorLog.error(e.getMessage(),e);
            e.printStackTrace();
            
        }finally{
            try{
                if(br!=null) br.close();
            }catch(IOException e){
                e.printStackTrace();
            }
            if(con!=null) con.disconnect();
        }
        if(response!=null) return response.toString();
        else return "nothing";
    }
    
    public static String setFormat(Map<String,String> map)
    {
        if(map.isEmpty()) return "";
        StringBuilder sb =new StringBuilder("{");
        for(Map.Entry<String, String> entry :map.entrySet())
        {
            if(sb.length()>1) sb.append(",");
            sb.append("\""+entry.getKey()+"\":\""+entry.getValue()+"\"");
        }
        sb.append("}");
        return sb.toString();
    }
    
    public static boolean checkURL(String url)
    {
        if(url==null) return false;
        String regex ="https?://.*";
        return Pattern.matches(regex, url);
    }

}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值