1. 引言
在HTTP协议中,Content-Type
头用于指示请求或响应中数据的媒体类型。了解和正确设置Content-Type
对于确保客户端和服务器之间正确解析数据至关重要。本文将介绍如何使用Java 和 不同的HTTP客户端发送各种Content-Type
类型的请求。
2. 常见的Content-Type
类型
以下是几种常见的Content-Type
类型及其应用场景:
-
application/json
- 描述: 用于发送JSON格式的数据。
- 传参方式: 通常在请求体中传递JSON字符串。
- 示例:
POST /api/data HTTP/1.1 Host: example.com Content-Type: application/json {"name": "John","age": 30 }
-
application/x-www-form-urlencoded
-
描述: 用于发送键值对数据,通常用于表单提交。
-
传参方式: 数据以键值对的形式编码在请求体中,格式类似于查询字符串。
-
示例:
POST /api/data HTTP/1.1 Host: example.com Content-Type: application/x-www-form-urlencodedname=John&age=30
请求头:
解析前:
解析后:
-
-
multipart/form-data
-
描述: 用于发送包含文件上传的表单数据。
-
传参方式: 数据以多部分形式编码,每部分包含一个表单字段或文件。
-
示例:
POST /api/data HTTP/1.12 Host: example.com3 Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW //指定分界线标识符------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="name"John -----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="file"; filename="example.txt"11 Content-Type: text/plain(file content)-----WebKitFormBoundary7MA4YWxkTrZu0gW--
请求头:
解析前:
解析后:
-
-
text/plain
- 描述: 用于发送纯文本数据。
- 传参方式: 数据以纯文本形式编码在请求体中。
- 示例:
POST /api/data HTTP/1.1 Host: example.com Content-Type: text/plainThis is plain text.
-
application/xml
- 描述: 用于发送XML格式的数据。
- 传参方式: 数据以XML格式编码在请求体中。
- 示例:
POST /api/data HTTP/1.1 Host: example.com Content-Type: application/xml<person><name>John</name><age>30</age> </person>
-
application/oct-stream
- 描述: 用于发送二进制数据,通常用于文件下载或上传。
- 传参方式: 数据以二进制形式编码在请求体中。
- 示例:
POST /api/data HTTP/1.1 Host: example.com Content-Type: application/octet-stream(binary data)
3. 使用Hutool发送HTTP请求
Hutool 是一个Java工具包,简化了日常开发中的许多任务。以下是使用Hutool发送各种Content-Type
类型的请求的示例代码。
1.安装Hutool
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.10</version>
</dependency>
2. 示例代码
1. application/json
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;public class JsonExample {public static void main(String[] args) {String url = "http://example.com/api/data";String json = JSONUtil.toJsonStr(Map.of("name", "John", "age", 30));HttpResponse response = HttpRequest.post(url).header("Content-Type", "application/json").body(json).execute();System.out.println(response.body());}
}
2. application/x-www-form-urlencoded
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;public class FormUrlEncodedExample {public static void main(String[] args) {String url = "http://example.com/api/data";Map<String,String> map = new HashMap();map.put("name", "John")map.put("age", "30") HttpResponse response = HttpRequest.post(url).header("Content-Type", "application/x-www-form-urlencoded").form(map).execute();System.out.println(response.body());}
}
3. multipart/form-data
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;public class MultipartExample {public static void main(String[] args) {String url = "http://example.com/api/data";Map<String,Object> map = new HashMap();map.put("name", "John")map.put("age", new File("path/to/your/file.txt")) HttpResponse response = HttpRequest.post(url).header("Content-Type", "multipart/form-data").form(map).execute();System.out.println(response.body());}
}
4. text/plain
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;public class PlainTextExample {public static void main(String[] args) {String url = "http://example.com/api/data";String text = "This is plain text.";HttpResponse response = HttpRequest.post(url).header("Content-Type", "text/plain").body(text).execute();System.out.println(response.body());}
}
5. application/xml
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;public class XmlExample {public static void main(String[] args) {String url = "http://example.com/api/data";String xml = "<person><name>John</name><age>30</age></person>";HttpResponse response = HttpRequest.post(url).header("Content-Type", "application/xml").body(xml).execute();System.out.println(response.body());}
}
6. application/octet-stream
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;public class OctetStreamExample {public static void main(String[] args) {String url = "http://example.com/api/data";byte[] data = "binary data".getBytes();HttpResponse response = HttpRequest.post(url).header("Content-Type", "application/octet-stream").body(data).execute();System.out.println(response.body());}
}
4. OkHttp
OkHttp是一个高效的HTTP客户端。以下是使用OkHttp发送各种Content-Type类型的请求的示例代码。
1. 安装OkHttp
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.9.3</version>
</dependency>
2. 示例代码
1. application/json
import okhttp3.*;import java.io.IOException;public class JsonExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";String json = "{\"name\":\"John\", \"age\":30}";OkHttpClient client = new OkHttpClient();RequestBody body = RequestBody.create(json, MediaType.parse("application/json"));Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {System.out.println(response.body().string());}}
}
2. application/x-www-form-urlencoded
import okhttp3.*;import java.io.IOException;public class FormUrlEncodedExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS).build();Map<String,String> map = new HashMap();map.put("name", "John")map.put("age", "30") // 构建请求体MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);// 动态添加文本参数for (Map.Entry<String, String> entry : map.entrySet()) {builder.addFormDataPart(entry.getKey(), entry.getValue());}Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {System.out.println(response.body().string());}}
}
3. multipart/form-data
import okhttp3.*;import java.io.File;
import java.io.IOException;public class MultipartExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";File file = new File("path/to/your/file.txt");OkHttpClient client = new OkHttpClient();RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("name", "John").addFormDataPart("file", file.getName(),RequestBody.create(file, MediaType.parse("application/octet-stream"))).build();Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {System.out.println(response.body().string());}}
}
4. text/plain
import okhttp3.*;import java.io.IOException;public class PlainTextExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";String text = "This is plain text.";OkHttpClient client = new OkHttpClient();RequestBody body = RequestBody.create(text, MediaType.parse("text/plain"));Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {System.out.println(response.body().string());}}
}
5. application/xml
import okhttp3.*;import java.io.IOException;public class XmlExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";String xml = "<person><name>John</name><age>30</age></person>";OkHttpClient client = new OkHttpClient();RequestBody body = RequestBody.create(xml, MediaType.parse("application/xml"));Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {System.out.println(response.body().string());}}
}
6. application/octet-stream
import okhttp3.*;import java.io.IOException;public class OctetStreamExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";byte[] data = "binary data".getBytes();OkHttpClient client = new OkHttpClient();RequestBody body = RequestBody.create(data, MediaType.parse("application/octet-stream"));Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {System.out.println(response.body().string());}}
}
5. Apache HttpClient
Apache HttpClient是一个强大的HTTP客户端,支持多种HTTP协议特性。以下是使用Apache HttpClient发送各种Content-Type类型的请求的示例代码。
1. 安装Apache HttpClient
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version>
</dependency>
2. 示例代码
1. application/json
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class JsonExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";String json = "{\"name\":\"John\", \"age\":30}";CloseableHttpClient client = HttpClients.createDefault();HttpPost post = new HttpPost(url);StringEntity entity = new StringEntity(json);entity.setContentType("application/json");post.setEntity(entity);try (CloseableHttpResponse response = client.execute(post)) {HttpEntity responseEntity = response.getEntity();if (responseEntity != null) {System.out.println(EntityUtils.toString(responseEntity));}}}
}
2. application/x-www-form-urlencoded
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;public class FormUrlEncodedExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";CloseableHttpClient client = HttpClients.createDefault();HttpPost post = new HttpPost(url);List<BasicNameValuePair> params = new ArrayList<>();params.add(new BasicNameValuePair("name", "John"));params.add(new BasicNameValuePair("age", "30"));HttpEntity entity = new UrlEncodedFormEntity(params);post.setEntity(entity);try (CloseableHttpResponse response = client.execute(post)) {HttpEntity responseEntity = response.getEntity();if (responseEntity != null) {System.out.println(EntityUtils.toString(responseEntity));}}}
}
3. multipart/form-data
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.File;
import java.io.IOException;public class MultipartExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";File file = new File("path/to/your/file.txt");CloseableHttpClient client = HttpClients.createDefault();HttpPost post = new HttpPost(url);HttpEntity entity = MultipartEntityBuilder.create().addTextBody("name", "John", ContentType.TEXT_PLAIN).addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()).build();post.setEntity(entity);try (CloseableHttpResponse response = client.execute(post)) {HttpEntity responseEntity = response.getEntity();if (responseEntity != null) {System.out.println(EntityUtils.toString(responseEntity));}}}
}
4. text/plain
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class PlainTextExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";String text = "This is plain text.";CloseableHttpClient client = HttpClients.createDefault();HttpPost post = new HttpPost(url);StringEntity entity = new StringEntity(text);entity.setContentType("text/plain");post.setEntity(entity);try (CloseableHttpResponse response = client.execute(post)) {HttpEntity responseEntity = response.getEntity();if (responseEntity != null) {System.out.println(EntityUtils.toString(responseEntity));}}}
}
5. application/xml
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class XmlExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";String xml = "<person><name>John</name><age>30</age></person>";CloseableHttpClient client = HttpClients.createDefault();HttpPost post = new HttpPost(url);StringEntity entity = new StringEntity(xml);entity.setContentType("application/xml");post.setEntity(entity);try (CloseableHttpResponse response = client.execute(post)) {HttpEntity responseEntity = response.getEntity();if (responseEntity != null) {System.out.println(EntityUtils.toString(responseEntity));}}}
}
6. application/octet-stream
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class OctetStreamExample {public static void main(String[] args) throws IOException {String url = "http://example.com/api/data";byte[] data = "binary data".getBytes();CloseableHttpClient client = HttpClients.createDefault();HttpPost post = new HttpPost(url);HttpEntity entity = new ByteArrayEntity(data);entity.setContentType("application/octet-stream");post.setEntity(entity);try (CloseableHttpResponse response = client.execute(post)) {HttpEntity responseEntity = response.getEntity();if (responseEntity != null) {System.out.println(EntityUtils.toString(responseEntity));}}}
}
6. RestTemplate
RestTemplate是Spring框架中的一个同步客户端,用于简化与HTTP服务器的通信。以下是使用RestTemplate发送各种Content-Type类型的请求的示例代码。
1. 安装Spring Boot Starter Web
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. 示例代码
1. application/json
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;import java.util.HashMap;
import java.util.Map;public class JsonExample {public static void main(String[] args) {String url = "http://example.com/api/data";Map<String, Object> json = new HashMap<>();json.put("name", "John");json.put("age", 30);RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<Map<String, Object>> entity = new HttpEntity<>(json, headers);String response = restTemplate.postForObject(url, entity, String.class);System.out.println(response);}
}
2. application/x-www-form-urlencoded
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;public class FormUrlEncodedExample {public static void main(String[] args) {String url = "http://example.com/api/data";RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);MultiValueMap<String, String> params = new LinkedMultiValueMap<>();params.add("name", "John");params.add("age", "30");HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);String response = restTemplate.postForObject(url, entity, String.class);System.out.println(response);}
}
3. multipart/form-data
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;public class MultipartExample {public static void main(String[] args) {String url = "http://example.com/api/data";String filePath = "path/to/your/file.txt";RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.MULTIPART_FORM_DATA);MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();params.add("name", "John");params.add("file", new FileSystemResource(filePath));HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);String response = restTemplate.postForObject(url, entity, String.class);System.out.println(response);}
}
4. text/plain
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;public class PlainTextExample {public static void main(String[] args) {String url = "http://example.com/api/data";String text = "This is plain text.";RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.TEXT_PLAIN);HttpEntity<String> entity = new HttpEntity<>(text, headers);String response = restTemplate.postForObject(url, entity, String.class);System.out.println(response);}
}
5. application/xml
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;public class XmlExample {public static void main(String[] args) {String url = "http://example.com/api/data";String xml = "<person><name>John</name><age>30</age></person>";RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_XML);HttpEntity<String> entity = new HttpEntity<>(xml, headers);String response = restTemplate.postForObject(url, entity, String.class);System.out.println(response);}
}
6. application/octet-stream
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;public class OctetStreamExample {public static void main(String[] args) throws Exception {String url = "http://example.com/api/data";Path path = Paths.get("path/to/your/file.txt");byte[] data = Files.readAllBytes(path);RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);HttpEntity<byte[]> entity = new HttpEntity<>(data, headers);String response = restTemplate.postForObject(url, entity, String.class);System.out.println(response);}
}