package webapi.demo;

import org.apache.commons.io.Charsets;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

import webapi.demo.pojo.DelTargetRequest;

/**
 * 删除图片接口演示
 * 
 * @author wangjun
 *
 */
public class DelTarget {
	/**
	 * 云数据库accessKey
	 */
	private String accessKey = "c900c450e04847eeb193496e03437830";
	/**
	 * 云数据库secretKey
	 */
	private String apiKey = "6a16240056e94454bccf942208633da0";
	/**
	 * 接口地址
	 */
	private String url = "https://cloud.voidar.net/develop/ws/deleteTarget.do";

	private String getRequestBody() {
		try {
			long id = 5201;// 图片ID
			DelTargetRequest requestBody = new DelTargetRequest(id);
			Gson gson = new Gson();
			return gson.toJson(requestBody);
		} catch (Exception e) {
			return null;
		}
	}

	private void postData() {
		CloseableHttpClient httpclient = HttpUtils.createSSLInsecureClient();
		CloseableHttpResponse response = null;
		try {
			String requestBody = this.getRequestBody();
			System.out.println(requestBody);
			if (StringUtils.isBlank(requestBody)) {
				System.out.println("请求数据错误");
				System.exit(1);
			}
			StringEntity entity = new StringEntity(requestBody);
			HttpPost post = new HttpPost(this.url);
			post.setHeader("Content-Type", "application/json");
			post.setHeader("Authorization", this.accessKey + ":" + this.apiKey);
			post.setEntity(entity);
			response = httpclient.execute(post);
			String resp = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
			System.out.println(resp);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (Exception e) {
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (Exception e) {
				}
			}
		}
	}

	public static void main(String[] args) {
		DelTarget task = new DelTarget();
		task.postData();
	}
}
