用java写一个支持application/x-www-form-urlencoded请求并切参数类型可以自定义的工具类
时间: 2023-09-26 16:11:20 浏览: 45
好的,我可以帮您解答这个问题。您可以使用Java中的HttpURLConnection类来发送application/x-www-form-urlencoded请求,并设置请求的参数类型为自定义类型。以下是一个简单的工具类示例代码:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUtils {
public static String sendPostRequest(String url, Map<String, String> params, String contentType) throws IOException {
URL requestUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", contentType);
String query = "";
for (Map.Entry<String, String> entry : params.entrySet()) {
if (!query.isEmpty()) {
query += "&";
}
query += URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
}
byte[] postData = query.getBytes(StandardCharsets.UTF_8);
connection.getOutputStream().write(postData);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
return response.toString();
}
}
```
您可以调用该类的sendPostRequest方法来发送请求,例如:
```
Map<String, String> params = new HashMap<>();
params.put("username", "john");
params.put("password", "password");
String response = HttpUtils.sendPostRequest("http://example.com/login", params, "application/x-www-form-urlencoded");
```
其中,第一个参数为请求的URL,第二个参数为请求的参数,第三个参数是Content-Type头部的值,这里设置为application/x-www-form-urlencoded。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)