JAVA:使用HttpURLConnection添加头部header信息并进行httpget请求
原创
©著作权归作者所有:来自51CTO博客作者奋斗咸鱼的原创作品,请联系作者获取转载授权,否则将追究法律责任
公用方法
import java.net.HttpURLConnection;
/**
* HttpGet请求
* @param vurl:请求地址,map:{头部信息}
* @return 返回消息
*/
public static String httpGet(String vurl,HashMap<String, Object> map) {
try {
URL url = new URL(vurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
for (Map.Entry item : map.entrySet()) {
connection.setRequestProperty(item.getKey().toString(),item.getValue().toString());//设置header
}
InputStream in = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(in, "utf-8");
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
isr.close();
in.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
使用示例
我们一般会在头部添加认证信息,如token值或BasicAuth认证的 Authorization值
HashMap<String, Object> tmap = new HashMap<String, Object>();
tmap.put("Authorization",authorization);//tmap.put("token","tonken值");
String vmsg= Comm.httpGet(vurl,tmap);//获取请求的返回结果