欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用spring-web类库实现httpget和httppost请求响应

程序员文章站 2022-06-14 22:41:40
...
好消息,百度网盘专业搜索网站上线了
打开瞧一瞧:http://bitar.cn



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

public class Test {

	public static void main(String[] args) throws IOException, URISyntaxException {
		String url = "https://www.baidu.com/img/bd_logo1.png";  
	    //①创建Http Request(内部使用HttpURLConnection)  
	    ClientHttpRequest request =   
	        new SimpleClientHttpRequestFactory().     
	            createRequest(new URI(url), HttpMethod.GET);  
	    //②设置客户端可接受的媒体类型(即需要什么类型的响应体数据)  
	    request.getHeaders().set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0");  
//	    request.getHeaders().set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");  
//	    request.getHeaders().set("Connection", "keep-alive");  
//	    request.getHeaders().set("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");  
	    //③发送请求并得到响应  
	    ClientHttpResponse response = request.execute();   
	    if (response.getStatusCode()==HttpStatus.OK) {
			System.out.println("ok");
		}
	    InputStream is = response.getBody();
	    //BufferedReader读取字符串
//		BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
//		String tempLine = br.readLine();
//		StringBuffer tempStr = new StringBuffer();
//		String crlf = System.getProperty("line.separator");
//		while (tempLine != null) {
//			tempStr.append(tempLine);
//			tempStr.append(crlf);
//			tempLine = br.readLine();
//		}
//		br.close();
//		is.close();
//		System.out.println(tempStr);
	    
	    //读取字节,再转为为字符串或者流
	    byte bytes[] = new byte[(int)response.getBody().available()];  
	    is.read(bytes);  
	    FileOutputStream fos=new FileOutputStream(new File("f:/a.png"));
	    fos.write(bytes,0,bytes.length);
	    fos.flush();
	    fos.close();
	    String xmlData = new String(bytes, Charset.forName("utf-8"));  
	    System.out.println(xmlData);  
		
	}

	

}


相关标签: java spring