import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kiisoo.open.base.palo.constants.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class HttpClientUtil {
/**
* PUT方法
* 使用流的方式上传数据至PALO
* @param inputStream 数据流
* @param url 地址
*/
@SuppressWarnings("resource")
public static JSONObject uploadPalo(InputStream inputStream,String url) throws Exception {
//返回结果对象
JSONObject json = new JSONObject();
//输入流的entity
HttpEntity entity = new InputStreamEntity(inputStream);
//http客户端
CloseableHttpClient httpclient = HttpClients.createDefault();
//定义一个put请求
HttpPut put = new HttpPut(url);
//设置请求头
put.setHeader("Expect", "100-continue");
put.setHeader("Authorization","Basic " + Base64.encode((Constants.PALO_AUTO).getBytes()));
//设置实体
put.setEntity(entity);
//执行
CloseableHttpResponse response = httpclient.execute(put);
//请求状态
int code = response.getStatusLine().getStatusCode();
//过滤状态
while(Constants.STATUS.contains(code)) {
//拿到新的url地址
Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD 中的
String uri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。
//设置
put.setURI(new URI(uri));
//继续请求
response = httpclient.execute(put);
code = response.getStatusLine().getStatusCode();
}
json.put("code", code);
//拿到返回结果
HttpEntity restEntity = response.getEntity();
String result = EntityUtils.toString(restEntity, "UTF-8");
//执行完后不是200表示失败
if(code != 200) {
json.put("msg", result);
}else {
json.putAll(JSON.parseObject(result));
}
return json;
}
public static void main(String[] args) throws Exception {
String url = "http://ip:8030/api/库名/表名/_load?label=版本&columns=id,name&column_separator=,";
List<String> list = new ArrayList<String>();
list.add("1001,张三");
list.add("1002,李四");
// 将work写入输出流,在装换成输入流
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.writeLines(list, "\n", out);
InputStream input = new ByteArrayInputStream(out.toByteArray());
//上传
uploadPalo(input, url);
}
}