公用方法

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);//获取请求的返回结果