java 使用URLConnection 进行HTTP接口调用

本文介绍如何使用Java中的URLConnection类实现GET请求,并通过示例展示了如何将对象属性映射到URL参数中,同时介绍了如何解析响应并将其转换为特定类型的Java对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java 使用URLConnection 进行HTTP接口调用 传递所需要的参数对象param url中的{参数}跟实体类中的属性命名一直会自动映射
//例如
public class Parameter{
    public static String operatorID="";
    public static String basic = "";
    public static String operatorPassword = "";
    public static String testFiled="";

    static {
        String projectType = PropertiesHander.getPropertiesValue("project.type");
        operatorID =  PropertiesHander.getPropertiesValue(projectType + ".av.operatorID");
        basic = PropertiesHander.getPropertiesValue(projectType + ".av.basic");
        operatorPassword = MD5Util.getMD5One((basic+operatorID).getBytes());
    }

}
String url="http://baidu.com/API/getUserInfoList?operatorID=${operatorID}&operatorPassword=${operatorPassword}";


package com.ig.gapi.common;import org.apache.log4j.Logger;import javax.xml.bind.JAXBContext;import javax.xml.bind.Unmarshaller;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.StringReader;import java.lang.reflect.Field;import java.net.URL;import java.net.URLConnection;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;import java.util.regex.Matcher;import java.util.regex.Pattern;

 public class CoreExecuteHttp { private static final Logger logger = Logger.getLogger(CoreExecuteAV.class); final static ConcurrentMap<Class,JAXBContext> contextCache = new ConcurrentHashMap<Class,JAXBContext>(); final static ConcurrentMap<Class,Field[]> fieldsCache = new ConcurrentHashMap<Class,Field[]>(); public static <T> T sendGet(Object parameter,Class<T> clazz,String url) { String result = ""; BufferedReader in = null; InputStreamReader inputStreamReader = null; InputStream inputStream = null; try { Field[] fields = fieldsCache.get(parameter.getClass()); if(fields == null){ fields = parameter.getClass().getFields(); fieldsCache.put(clazz,fields); } for (int i = 0; i < fields.length; i++) { Field filed = fields[i]; String filedName = filed.getName(); Object value = null; try { value = filed.get(parameter); } catch (IllegalAccessException e) { e.printStackTrace(); } if(value != null){ url = url.replace("${"+filedName+"}", value.toString()); } } url = url.replaceAll("&[^\\&]*=\\$\\{.*?\\}", ""); Pattern pattern = Pattern.compile("\\?.*?\\$\\{.*?\\}"); Matcher matcher = pattern.matcher(url); if(matcher.find()){ String matchUrl = matcher.group(0); url = url.replace(matchUrl.substring(1), ""); } System.out.println(url); URL realUrl = new URL(url.trim()); URLConnection connection = realUrl.openConnection(); connection.setConnectTimeout(20000); connection.setReadTimeout(20000); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.connect(); Map<String, List<String>> map = connection.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } inputStream = connection.getInputStream(); inputStreamReader = new InputStreamReader(inputStream); in = new BufferedReader(inputStreamReader); String line; while ((line = in.readLine()) != null) { result += line; } JAXBContext context = contextCache.get(clazz); if(context == null){ context = JAXBContext.newInstance(clazz); contextCache.put(clazz,context); } Unmarshaller jaxbUnmarshaller = context.createUnmarshaller(); StringReader stringReader = new StringReader(result); return (T) jaxbUnmarshaller.unmarshal(stringReader); } catch (Exception e) { System.out.println("aa链接请求 " + e); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if(inputStreamReader!=null){ inputStreamReader.close(); } if(inputStream!=null){ inputStream.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return null; }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值