使用java,写一段代码,实现通过HttpUtil 调用第三方接口,传入list集合,并实现数据新增
时间: 2024-05-12 16:16:58 浏览: 125
好的,对于您的问题,我会根据您的要求给出一个使用Java编写的代码段,实现通过HttpUtil调用第三方接口,并传入List集合进行新增数据操作。下面是代码:
```
import java.io.IOException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpUtil {
public static boolean addData(String url, List<MyData> dataList) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
String json = dataListToJson(dataList);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
HttpResponse response;
try {
response = httpclient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String responseJson = EntityUtils.toString(responseEntity);
if (responseJson.contains("success")) {
return true;
}
return false;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
private static String dataListToJson(List<MyData> dataList) {
StringBuilder jsonBuilder = new StringBuilder("[");
for (MyData data : dataList) {
jsonBuilder.append("{");
jsonBuilder.append("\"name\":").append(data.getName()).append(",");
jsonBuilder.append("\"age\":").append(data.getAge());
jsonBuilder.append("},");
}
jsonBuilder.setCharAt(jsonBuilder.length() - 1, ']');
return jsonBuilder.toString();
}
}
class MyData {
private String name;
private int age;
// constructor, getters, setters
// ...
}
```
我希望这段代码可以满足您的需求,如果您有任何其他问题或需要,都可以随时向我提出。
阅读全文