palo資料庫小批量http上傳資料工具類
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); } }