java如何在一个项目调另一个项目中“post--/project/v1/mdg/identity/project/queryAllProject”类型的接口,并举例?
时间: 2023-09-18 17:09:40 浏览: 222
Master Data Governance for Custom Objects自定义对象的主数据管理
Java可以使用HttpURLConnection或者HttpClient这两个类库调用其他项目的接口。
下面是使用HttpClient调用其他项目接口的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/project/v1/mdg/identity/project/queryAllProject");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们使用了HttpPost类来发送POST请求,并传递参数。params是一个List,包含了所有的参数名和参数值。UrlEncodedFormEntity类将params转换成了POST请求的参数格式。
需要注意的是,这里的URL是示例代码中的URL,需要替换成实际的接口URL。另外,如果接口需要传递JSON格式的数据,则需要使用HttpEntity和StringEntity类来构造请求体。
阅读全文