java 接口 指定 content-type: application/x-www-form-urlencoded
时间: 2023-07-29 11:12:06 浏览: 204
在Java中指定`content-type`为`application/x-www-form-urlencoded`有多种方式,以下是其中两种常见的方法:
1. 使用`HttpURLConnection`发送POST请求时,可以通过设置`setRequestProperty`方法来指定`content-type`为`application/x-www-form-urlencoded`,示例代码如下:
```
URL url = new URL("your_url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 组装请求参数
String params = "param1=value1¶m2=value2";
// 向服务器写入参数
OutputStream outputStream = conn.getOutputStream();
outputStream.write(params.getBytes());
outputStream.flush();
// 获取响应结果
int responseCode = conn.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseBody = response.toString();
```
2. 使用第三方库`OkHttp`发送POST请求时,可以通过设置`MediaType`为`MediaType.parse("application/x-www-form-urlencoded")`来指定`content-type`,示例代码如下:
```
OkHttpClient client = new OkHttpClient();
String url = "your_url";
String params = "param1=value1¶m2=value2";
RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), params);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
```
阅读全文