目录
OkHttpClient
get
post+form
post+json
HttpClient
get
post+form
post+json
RestTemplate
get
post+form
post+json
URL下载文件
服务端
客户端
上传文件
客户端
服务端
OkHttpClient
pom依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.5.0</version>
</dependency>
get
- 客户端
Request request = new Request.Builder()
.url("http://localhost:8080/testGet?name=1&age=2")
.build();
try {
String responseStr = null;
Response response = new OkHttpClient().newCall(request).execute();
if (!response.isSuccessful()) {
System.out.println("请求失败");
return;
}
responseStr = response.body().string();
System.out.println("请求结果responseStr:" + responseStr);
} catch (Exception e) {
System.out.println(e);
}
- 服务器端
@RequestMapping("/testGet")
@ResponseBody
public String testGet(@RequestParam("name") String name, @RequestParam("age") String age) {
System.out.println("name: "+name + " age:" + age);
return "success";
}
注:如果客户端无法连接服务器端会报出:java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:8080 异常 被Exception 捕获。
post+form
- 客户端
String path = "http://localhost:8080/testPostForm1";
// 1 创建okhttpclient对象
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder().add("name", "11").add("age", "222").build();
// 2 创建请求方式
Request request = new Request.Builder().url(path).post(body).build();
// 3 执行请求操作
try {
Response response = okHttpClient.newCall(request).execute();
if(response.isSuccessful()){
String string = response.body().string();
System.out.println(string);
}
} catch (IOException e) {
e.printStackTrace();
}
- 服务端
@RequestMapping("/testPostForm1")
@ResponseBody
public String testPostForm1(@RequestParam("name") String name, @RequestParam("age") String age) {
System.out.println("testPostForm1 name: "+name + " age:" + age);
return "success";
}
或
@RequestMapping("/testPostForm2")
@ResponseBody
public String testPostForm2(Model model) {
System.out.println("testPostForm2 name: "+model.getName() + " age:" + model.getAge());
return "success";
}
post+json
- 客户端
ParamModel paramModel = new ParamModel();
paramModel.setName("111");
paramModel.setAge(222);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:8080/testPostJson")
.header("Content-Type","application/json")// 不加header也好使
.post(RequestBody.create(MediaType.parse("application/json;charset=utf-8")
, JSON.toJSONString(paramModel)))
.build();
try {
String responseStr = null;
Response response = okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) {
System.out.println("请求失败");
}
responseStr = response.body().string();
System.out.println("====>"+responseStr);
} catch (IOException e) {
System.out.println("请求异常"+e);
}
- 服务端
@RequestMapping("/testPostJson")
@ResponseBody
public String testPostJson(@RequestBody Model model) {
System.out.println("testPostJson name: "+model.getName() + " age:" + model.getAge());
return "success";
}
HttpClient
pom依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
get
服务端代码同OkHttpClient get服务端代码。
String result = "";
HttpGet httpGet = new HttpGet("http://localhost:8080/testGet?name=1&age=2");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
System.out.println("请求成功出参==>" + result);
}
输出:请求成功出参==>success
post+form
服务端代码同OkHttpClient post服务端代码。
String result = "";
HttpPost httpPost = new HttpPost("http://localhost:8080/testPostForm1");
Map<String, String> params = Maps.newHashMap();
params.put("name", "张三");
params.put("age", "20");
if (null != params && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair = null;
for (String key : params.keySet()) {
pair = new BasicNameValuePair(key, params.get(key));
pairs.add(pair);
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,Charset.forName("UTF-8"));
httpPost.setEntity(entity);
}
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
System.out.println("请求成功出参==>" + result);
}
输出:请求成功出参==>success
post+json
服务端代码同OkHttpClient post+json服务端代码。
String result = "";
HttpPost httpPost = new HttpPost("http://localhost:8080/testPostJson");
Map<String, String> params = Maps.newHashMap();
params.put("name", "张三");
params.put("age", "20");
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(JSON.toJSONString(params), Charset.forName("UTF-8")));
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
System.out.println("请求成功出参==>" + result);
}
RestTemplate
在基于Spring的项目中可以使用RestTemplate
初始配置
声明restTemplate Bean
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.getInterceptors().add(new HttpApiLogInterceptor()); // 拦截器配置
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(150000); // ms
factory.setConnectTimeout(150000); // ms
return factory;
}
}
get
服务端代码同OkHttpClient get服务端代码。
客户端
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/testGet")
@ResponseBody
public String testGet() {
String res = restTemplate.getForObject("http://localhost:8080/testGet?name=1&age=2", String.class);
System.out.println("出参===》"+res);
return res;
}
输出:出参===》success
post+form
服务端代码同OkHttpClient post服务端代码。
客户端
@RequestMapping("/testPostForm")
@ResponseBody
public String testPostForm() {
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
//接口参数
map.add("name", "11");
map.add("age", "222");
//头部类型
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//构造实体对象
HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);
//发起请求,服务地址,请求参数,返回消息体的数据类型
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/testPostForm1", param, String.class);
//body
String body = response.getBody();
System.out.println("body===>" + body);
//如果出参是JSON格式的字符串可以进行如下转化
// Map result = JSON.parseObject(body, Map.class);
// System.out.println("result==>"+JSON.toJSONString(result));
return "success";
}
输出:body===>success
post+json
服务端代码同OkHttpClient post+json服务端代码。
客户端
@RequestMapping("/testPostJson")
@ResponseBody
public String testPostJson() throws Exception {
Model model = new Model();
model.setAge(222);
model.setName("1111");
// 注意下面这三句
HttpHeaders headers = new HttpHeaders();
//头部类型
headers.setContentType(MediaType.APPLICATION_JSON);
//构造实体对象
HttpEntity<String> param = new HttpEntity<>(JSON.toJSONString(model), headers);
//发起请求,服务地址,请求参数,返回消息体的数据类型
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/testPostJson", param, String.class);
//body
String body = response.getBody();
System.out.println("body===>" + body);
return "success";
}
输出:body===>success
附:restTemplate拦截器配置
public class HttpApiLogInterceptor implements ClientHttpRequestInterceptor {
private Logger logger= LoggerFactory.getLogger(HttpApiLogInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
long startMills=System.currentTimeMillis();
ClientHttpResponse response= null;
String resShowText=null;
try {
response=execution.execute(request, body);
}catch (Exception e){
logger.error("异常",e);
resShowText=e.getMessage();
}
long endMills=System.currentTimeMillis();
if(response!=null){
resShowText=response.getStatusText()+","+response.getRawStatusCode();
}
logger.info("请求情况:耗时:{}毫秒,地址:{} | 请求方法: {} | 请求内容:{} | 请求头:{} |结果{}", endMills-startMills,request.getURI(),
request.getMethod(),
new String(body),
request.getHeaders(),resShowText);
return response;
}
}
URL下载文件
服务端
@RequestMapping("/testDownLoad")
@ResponseBody
public void testDownLoad(HttpServletResponse response) throws IOException {
// 输出流(输出到网络)
ServletOutputStream outputStream = response.getOutputStream();
// 读取本地文件
File file = new File("/data/test/test.zip");
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bf = new BufferedInputStream(fileInputStream);
byte[] bytes = new byte[1024];
int len = 0;
// 输入流(从磁盘输入)每次读取有效的字节数
while ((len = bf.read(bytes)) != -1) {
// 把有效的字节写到输出流(输出到网络)中
outputStream.write(bytes, 0, len);
}
outputStream.close();
}
客户端
// get方式+原生方法
try {
URL httpUrl = new URL("http://localhost:8081/testDownLoad");
InputStream inputStream = httpUrl.openStream();
byte[] bytes = new byte[1024];
int len = 0;
String fileNameAnPath = "/data/test/1.txt";
File f = new File(fileNameAnPath);
if (f.exists()) {
f.delete();
}
// 当已存在file时,如果第二个参数为true,选在向该文件末尾追加
// FileOutputStream fileOutputStream = new FileOutputStream(f,true);
FileOutputStream fileOutputStream = new FileOutputStream(f);
while ((len = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
// get方式+工具类
try {
URL httpUrl = new URL("http://localhost:8081/testDownLoad");
String fileNameAnPath = "/data/test/2.txt";
File f = new File(fileNameAnPath);
if (f.exists()) {
f.delete();
}
// 获取
FileUtils.copyURLToFile(httpUrl, f);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
// post方式+工具类
Request request = new Request.Builder()
.url("http://localhost:8081/testDownLoad")
.build();
try {
Response response = new OkHttpClient().newCall(request).execute();
if (!response.isSuccessful()) {
System.out.println("请求失败");
return;
}
byte[] bytes = response.body().bytes();
System.out.println(bytes.length);
String fileNameAnPath = "/data/test/3.txt";
Files.write(Paths.get(fileNameAnPath), bytes, StandardOpenOption.CREATE);
} catch (Exception e) {
System.out.println("下载异常");
}
上传文件
客户端
<form id="ff_addFile" method="post" action="" enctype="multipart/form-data">
<input type="file" id="id-input-file-1" name="files" enctype="multipart/form-data">
</label>
<button type="button" id="file_submit" onclick="upLoadFile()">
提交
</button>
</form>
function upLoadFile(){
var form = $('#ff_addFile')[0];
var formData = new FormData(form);
$("#up_text1").show();
$.ajax({
url: "http://localhost:8081/fileUpload",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (data) {
if (success) {
alert("上传成功");
}
else {
alert(data);
}
},
error: function () {
alert("上传失败");
}
});
}
服务端
@PostMapping(value = "/fileUpload")
@ResponseBody
public String fileUpload(@Valid FileRequest request, BindingResult error) {
List<FileRequest> channelFeeStatements = new ArrayList<>();
if (error.hasErrors()) {
return "error";
}
if (CollectionUtils.isEmpty(request.getFiles()) && request.getFiles().size() > 1) {
return "error";
}
try {
// 获取输入流(网络-->内存)
MultipartFile multipartFile = request.getFiles().get(0);
InputStream inputStream = multipartFile.getInputStream();
long size = multipartFile.getSize();
byte[] res = multipartFile.getBytes();
System.out.println(size);
System.out.println(res.length);
// 原始文件名称
String originalFilename = multipartFile.getOriginalFilename();
byte[] bytes = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = new FileOutputStream(new File("/data/temp/" + originalFilename));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
// 上传文件读入到数组
while ((len = inputStream.read(bytes)) != -1) {
// 数组写出到本地文件
bufferedOutputStream.write(bytes,0, len);
}
// 如果用BufferedOutputStream记得刷新/关闭流,否则会丢失字节
bufferedOutputStream.flush();
bufferedOutputStream.close();
fileOutputStream.close();
} catch (Exception e) {
}
return "success";
}
@Data
public class FileRequest {
private List<MultipartFile> files;
}