Http请求工具类 怎么使用application/x-www-form-urlencoded
时间: 2023-07-29 15:15:02 浏览: 49
使用Http请求工具类发送 application/x-www-form-urlencoded 格式的数据,需要按照以下步骤:
1. 创建一个HttpURLConnection对象,设置请求方式为POST,设置请求URL地址。
2. 设置请求头部信息,包括Content-Type和Content-Length两个参数。Content-Type设置为application/x-www-form-urlencoded,Content-Length设置为请求参数的长度。
3. 获取输出流,将请求参数写入输出流中,使用URL编码方式进行编码。
4. 发送请求,获取响应结果。
下面是一个Java代码示例,演示如何使用HttpURLConnection发送 application/x-www-form-urlencoded 格式的数据:
```
public static String sendPost(String url, Map<String, String> params) throws Exception {
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String response = "";
String inputLine;
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
in.close();
return response;
}
```
其中,params为请求参数,类型为Map<String, String>,url为请求地址。在该示例中,使用了URLEncoder对参数进行编码。