java利用RestTemplate发送http请求,在请求中添加header

public static String get() throws Exception{
	RestTemplate restTemplate = new RestTemplate();
	/** 接口返回值 */
	StringBuilder result = new StringBuilder();
	/** 请求头 */
	HttpHeaders headers = new HttpHeaders();
	MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
	headers.setContentType(type);
	headers.add("Accept", "*/*");
	HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
	/** 在请求中添加请求头 */
	ResponseEntity<Resource> entity = restTemplate.getForEntity(url, Resource.class,httpEntity);
	InputStream in = entity.getBody().getInputStream();
	BufferedReader br = new BufferedReader(new InputStreamReader(in));
	while ((ret = br.readLine()) != null)
	{
	if (ret != null && !ret.trim().equals(""))
	     {
	         result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
	     }
	}
	br.close();
	return result.toString();
}

你可能感兴趣的:(后端,Java)