在Java中,调用第三方接口通常可以通过HTTP客户端库来实现,例如Apache HttpClient。以下是一个使用Apache HttpClient发起GET请求的基本示例:
import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;public class ThirdPartyApiCall {public static void main(String[] args) {String url = "http://api.example.com/thirdparty/api";try {CloseableHttpClient httpClient = HttpClients.createDefault();HttpGet request = new HttpGet(url);HttpResponse response = httpClient.execute(request);String result = EntityUtils.toString(response.getEntity());System.out.println("得到第三方接口内容: " + result);} catch (IOException e) {e.printStackTrace();}}}
如果你需要发送POST请求,可以使用以下示例代码:
import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.UrlEncodedFormEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;public class ThirdPartyApiCall {public static void main(String[] args) {String url = "http://api.example.com/thirdparty/api";try {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");Listnvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("VId", "xxx"));nvps.add(new BasicNameValuePair("password", "xxx"));nvps.add(new BasicNameValuePair("telephone", "xxx"));nvps.add(new BasicNameValuePair("nickName", "xxx"));httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));HttpResponse response = httpClient.execute(httpPost);String result = EntityUtils.toString(response.getEntity());System.out.println("得到第三方接口内容: " + result);} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}
请注意,上述代码示例使用了Apache HttpClient 4.5.13版本,如果你使用的是不同的版本,可能需要对代码进行相应的调整。

