java发送x-www-form-urlencoded请求
时间: 2023-11-08 16:00:36 浏览: 110
Java发送x-www-form-urlencoded请求可以通过使用HttpURLConnection或者Apache HttpClient来实现。以下是使用HttpURLConnection的示例代码:
```java
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Main {
public static void main(String[] args) {
String url = "https://example.com/api";
String data = "param1=value1¶m2=value2";
try {
URL endpoint = new URL(url);
HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(data);
outputStream.flush();
outputStream.close();
// 获取响应
int responseCode = connection.getResponseCode();
// 处理响应数据...
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文