java中怎么调用第三方接口,推送数据
时间: 2024-06-09 19:07:48 浏览: 169
Java调用第三方接口,一般可以使用HttpURLConnection或者HttpClient来实现。下面是一个简单的使用HttpURLConnection调用第三方接口的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpUtil {
/**
* 发送HTTP GET请求,并返回响应结果
* @param url 请求地址
* @return 响应结果
*/
public static String sendGet(String url) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder result = new StringBuilder();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
if (connection.getResponseCode() == 200) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} else {
System.out.println("请求失败,状态码:" + connection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result.toString();
}
/**
* 发送HTTP POST请求,并返回响应结果
* @param url 请求地址
* @param params 请求参数
* @return 响应结果
*/
public static String sendPost(String url, String params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder result = new StringBuilder();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.getOutputStream().write(params.getBytes("UTF-8"));
connection.connect();
if (connection.getResponseCode() == 200) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} else {
System.out.println("请求失败,状态码:" + connection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result.toString();
}
}
```
使用示例:
```java
String url = "http://example.com/api?param1=value1¶m2=value2";
String result = HttpUtil.sendGet(url);
System.out.println(result);
String url = "http://example.com/api";
String params = "param1=" + URLEncoder.encode("value1", "UTF-8") + "¶m2=" + URLEncoder.encode("value2", "UTF-8");
String result = HttpUtil.sendPost(url, params);
System.out.println(result);
```
推送数据到第三方接口,一般需要使用POST请求,并在请求体中携带数据。具体实现方式取决于第三方接口的要求,可以使用上面的示例代码进行参考。
阅读全文