Spring RestTemplate 得到HttpStatus,并读取get的body内容

58 篇文章 0 订阅
6 篇文章 0 订阅
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:sec="http://www.springframework.org/schema/security"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"

	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">


	<bean id="template" class="org.springframework.web.client.RestTemplate">
		<constructor-arg>
			<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"/>
		</constructor-arg>
	</bean>

	
</beans>

 

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

/**
 * <pre>
 * Example01.java
 * @author kanpiaoxue<br>
 * @version 1.0
 * Create Time 2015年1月20日 下午2:59:00<br>
 * Description :类实现描述
 * </pre>
 */
public class Example01 {
    
    public static URI createUri(String host, int port, String path,
            Object... args) {
        UriComponents uriComponents = UriComponentsBuilder.newInstance()
                .port(port).scheme("http").host(host).path(path).build();
        if (null != args && args.length > 0) {
            uriComponents.expand(args);
        }
        uriComponents.encode();
        return uriComponents.toUri();
    }

    /**
     * <pre>
     * @param args
     * </pre>
     */
    public static void init(String[] args) {
        context = new FileSystemXmlApplicationContext(
                "D:/baidu/workspaces/workspace_java/test/src/main/java/com/baidu/learn/spring/restTemplate/spring-ctx-application.xml");
        template = context.getBean("template", RestTemplate.class);
    }

    public static void main(String[] args) {
        init(args);
        // ===========================
        Example01 e = new Example01();
        e.testHttpCode();
        e.testHttpLog();
    }

    private static ApplicationContext context;

    private static RestTemplate template;

    private final String url = "http://cp01-rd-crm-cdc-db05.cp01.baidu.com:8097/dispatch-cdc-etl-test-leader-4597-20150120041830-ShellRunner-0.out";

    /**
     * <pre>
     * @param template
     * @param url
     * @return 是否2xx的成功状态
     * </pre>
     */
    private boolean is2xxSuccessful(RestTemplate template, String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "text/html");
        headers.add(
                "Accept",
                "text/html,application/xhtml+xml,application/xml,application/json;q=0.9,image/webp,*/*;q=0.8");
        headers.add("Accept-Encoding", "gzip, deflate, sdch");
        headers.add("Cache-Control", "max-age=0");
        headers.add("Connection", "keep-alive");
        HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
        ResponseEntity<String> responseEntity = template.exchange(url,
                HttpMethod.GET, requestEntity, String.class);
        HttpStatus status = responseEntity.getStatusCode();
        return status.is2xxSuccessful();
    }

    /**
     * <pre>
     * @param template
     * @param url
     * @return 读取远程url的文件内容
     * </pre>
     */
    private String readContentFromRemote(RestTemplate template, String url) {
        ResponseEntity<String> entity = template
                .getForEntity(url, String.class);
        return entity.getBody();
    }

    private void testHttpCode() {
        boolean is2xxSuccessful = is2xxSuccessful(template, url);
        System.out.println(String.format("url:%s : %s", url, is2xxSuccessful));
    }

    private void testHttpLog() {
        String body = readContentFromRemote(template, url);
        System.out.println(body);
    }
}

 

 

首先,您需要定义一个包含图片数据的实体类,并使用JPA注解将其映射到数据库中的一张表。例如,以下是一个包含图片数据的实体类的示例: ```java @Entity @Table(name = "image") public class ImageEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Lob private byte[] data; // getters and setters } ``` 其中,`data` 属性使用了 `@Lob` 注解,表示将其映射为数据库中的大对象类型。 接下来,在Spring Boot中定义一个RESTful的API,用于接收前端上传的图片数据,并将其存储到数据库中。例如: ```java @RestController @RequestMapping("/api/images") public class ImageController { @Autowired private ImageRepository imageRepository; @PostMapping("/upload") public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) { try { ImageEntity imageEntity = new ImageEntity(); imageEntity.setName(file.getOriginalFilename()); imageEntity.setData(file.getBytes()); imageRepository.save(imageEntity); return ResponseEntity.ok().build(); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Failed to upload image"); } } @GetMapping("/{id}") public ResponseEntity<byte[]> getImage(@PathVariable("id") Long id) { Optional<ImageEntity> optional = imageRepository.findById(id); if (optional.isPresent()) { ImageEntity imageEntity = optional.get(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); return new ResponseEntity<>(imageEntity.getData(), headers, HttpStatus.OK); } else { return ResponseEntity.notFound().build(); } } } ``` 其中,`uploadImage` 方法用于接收前端上传的图片数据,并将其存储到数据库中;`getImage` 方法用于根据图片的ID从数据库中读取图片数据,并返回给前端。 最后,在Vue前端中使用 `axios` 或其他HTTP库发送请求,上传图片并显示。例如: ```vue <template> <div> <input type="file" @change="uploadImage"> <img :src="imageUrl" v-if="imageUrl"> </div> </template> <script> import axios from 'axios'; export default { data() { return { imageUrl: null }; }, methods: { uploadImage(event) { const file = event.target.files[0]; const formData = new FormData(); formData.append('file', file); axios.post('/api/images/upload', formData) .then(() => this.fetchImage()) .catch(error => console.error(error)); }, fetchImage() { axios.get(`/api/images/${id}`, { responseType: 'arraybuffer' }) .then(response => { const imageUrl = URL.createObjectURL(new Blob([response.data], { type: 'image/jpeg' })); this.imageUrl = imageUrl; }) .catch(error => console.error(error)); } } }; </script> ``` 其中,`uploadImage` 方法用于上传图片数据;`fetchImage` 方法用于根据图片的ID从后端获取图片数据,并使用 `Blob` 对象将其转换为URL,以便在 `<img>` 标签中显示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值