java发送带Basic Auth认证的http post请求实例代码
时间: 2024-02-05 08:04:00 浏览: 152
以下是Java发送带Basic Auth认证的HTTP POST请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class HttpPostWithBasicAuth {
public static void main(String[] args) throws IOException {
String url = "http://example.com/api/resource";
String username = "myusername";
String password = "mypassword";
String postData = "param1=value1¶m2=value2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// set request method
con.setRequestMethod("POST");
// set basic authentication header
String auth = username + ":" + password;
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
con.setRequestProperty("Authorization", authHeaderValue);
// set post data
con.setDoOutput(true);
con.getOutputStream().write(postData.getBytes("UTF-8"));
// get response
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print response
System.out.println("Response code: " + responseCode);
System.out.println("Response body: " + response.toString());
}
}
```
在上面的代码中,我们使用 `HttpURLConnection` 类来建立HTTP连接,并设置了请求头中的基本认证信息。我们还设置了POST数据,并获取了响应,最后打印了响应码和响应体。请注意,此示例仅用于演示目的,实际使用中需要根据实际情况进行修改。
阅读全文