java调用http接口,并在调用前传用户名和密码参数
时间: 2024-03-17 16:42:54 浏览: 141
http_java调用
你可以使用Java中的HttpURLConnection类来调用http接口,并在调用前传用户名和密码参数。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class HttpUrlConnectionExample {
public static void main(String[] args) {
try {
String username = "your_username";
String password = "your_password";
String url = "http://example.com/api";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// set request method
con.setRequestMethod("GET");
// set basic authentication header
String auth = username + ":" + password;
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes());
String authHeaderValue = "Basic " + new String(encodedAuth);
con.setRequestProperty("Authorization", authHeaderValue);
// read response
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.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们首先设置了要调用的API的URL、用户名和密码。然后我们使用Java的Base64类来编码用户名和密码,以便将其添加到http请求标头中。最后,我们使用HttpURLConnection类来执行GET请求,并读取响应。
阅读全文