java发送from-data格式请求
时间: 2023-12-18 21:02:48 浏览: 21
Java发送from-data格式请求可以使用Java的HttpURLConnection类来实现。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class FormDataRequest {
public static void main(String[] args) {
try {
String url = "http://example.com/api";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置请求参数
String params = "name=" + URLEncoder.encode("John", "UTF-8") + "&age=30";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
// 发送请求
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先创建了一个HTTP连接对象,并设置了请求方法、请求头和请求参数。然后,我们通过输出流将请求参数写入到请求体中,发送请求并读取响应。最后,我们将响应输出到控制台。
注意,我们使用了URLEncoder.encode()方法来对请求参数进行编码,这是因为在from-data格式中,请求参数需要进行URL编码。