java通过http请求工具类(包含文件传输)

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Formatter;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.xpath.operations.Bool;

import com.fintech.third.utils.Base64Util;
import com.fintech.third.utils.SystemUtil;

import net.sf.json.JSONObject;

public class HttpClientEntityPost {
    private static Logger logger = Logger.getLogger(HttpClientEntityPost.class);

    private static final String HASH_ALGORITHM = "HmacSHA256";

    static String timestamp = Long.toString(System.currentTimeMillis());
    static String nonce = RandomStringUtils.randomAlphanumeric(16);

    public static String httpClientEntityPost(String postUrl, JSONObject jsonObject)
            throws ClientProtocolException, IOException {
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        HttpClient httpclient = new DefaultHttpClient();
        String line = "";
        HttpPost post = new HttpPost(postUrl);
        StringBody id = new StringBody(jsonObject.get("api_id").toString());
        StringBody secret = new StringBody(jsonObject.get("api_secret").toString());
        StringBody name = new StringBody(jsonObject.get("user_name").toString(), contentType);
        StringBody number = new StringBody(jsonObject.get("id_number").toString());
        MultipartEntity entity = new MultipartEntity();

        entity.addPart("api_id", id);
        entity.addPart("api_secret", secret);
        entity.addPart("name", name);
        entity.addPart("id_number", number);
        post.setEntity(entity);

        try {
            HttpResponse response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entitys = response.getEntity();
                BufferedReader reader = new BufferedReader(new InputStreamReader(entitys.getContent()));
                line = reader.readLine();
                System.out.println(line);
            } else {
                HttpEntity r_entity = response.getEntity();
                line = EntityUtils.toString(r_entity);
                logger.info("错误码是:" + response.getStatusLine().getStatusCode() + "  "
                        + response.getStatusLine().getReasonPhrase());
                logger.info("出错原因是:" + line);
                // 你需要根据出错的原因判断错误信息,并修改
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("============>>>>请求" + e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }

        return line;
    }

    public static String httpClientPost(String postUrl, JSONObject jsonObject)
            throws ClientProtocolException, IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        String line = "";
        HttpClient httpclient = new DefaultHttpClient();

        HttpPost post = new HttpPost(postUrl);
        StringBody id = new StringBody(jsonObject.get("api_id").toString());
        StringBody secret = new StringBody(jsonObject.get("api_secret").toString());
        StringBody name = new StringBody(jsonObject.get("user_name").toString(), Charset.forName("UTF-8"));
        StringBody number = new StringBody(jsonObject.get("id_number").toString());
        StringBody selfie_auto_rotate = new StringBody(jsonObject.get("selfie_auto_rotate").toString());
        String filePath = Base64Util.generateImageByCodec(jsonObject.get("image_base64").toString(),
                simpleDateFormat.format(new Date()) + jsonObject.get("id_number").toString() + ".jpg");
        FileBody fileBody = new FileBody(new File(filePath));
        MultipartEntity entity = new MultipartEntity();

        entity.addPart("api_id", id);
        entity.addPart("api_secret", secret);
        entity.addPart("name", name);
        entity.addPart("id_number", number);
        entity.addPart("selfie_file", fileBody);
        entity.addPart("selfie_auto_rotate", selfie_auto_rotate);
        post.setEntity(entity);
        try {
            HttpResponse response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entitys = response.getEntity();
                BufferedReader reader = new BufferedReader(new InputStreamReader(entitys.getContent()));
                line = reader.readLine();
                logger.info("=======>>line" + line);
            } else {
                HttpEntity r_entity = response.getEntity();
                line = EntityUtils.toString(r_entity);
                logger.info("错误码是:" + response.getStatusLine().getStatusCode() + "  "
                        + response.getStatusLine().getReasonPhrase());
                logger.info("出错原因是:" + line);
                // 你需要根据出错的原因判断错误信息,并修改
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("============>>>>请求" + e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return line;
    }

    public static String postFile(String filePath, String url, Map<String, String> map)
            throws ClientProtocolException, IOException {
        String line = "";
        FileBody bin = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity();
        for (String key : map.keySet()) {
            logger.info("key:" + key + "-------value:" + map.get(key));
            entity.addPart(key, new StringBody(map.get(key), Charset.forName("UTF-8")));
        }
        if (StringUtils.isNotEmpty(filePath)) {
            FileBody fileBody = new FileBody(new File(filePath));
            entity.addPart("contract_file", fileBody);
        }
        httppost.setEntity(entity);

        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entitys = response.getEntity();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entitys.getContent()));
            line = reader.readLine();
            logger.info("=======>>line" + line);
        } else {
            HttpEntity r_entity = response.getEntity();
            line = EntityUtils.toString(r_entity);
            logger.info("错误码是:" + response.getStatusLine().getStatusCode() + "  "
                    + response.getStatusLine().getReasonPhrase());
            logger.info("出错原因是:" + line);
            // 你需要根据出错的原因判断错误信息,并修改
        }
        httpclient.getConnectionManager().shutdown();
        return line;
    }

    
    
    public static String postFile2(String filePath,String fileParamsName, String url, Map<String, String> map)
            throws ClientProtocolException, IOException {
        String line = "";
        FileBody bin = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity();
        for (String key : map.keySet()) {
            logger.info("key:" + key + "-------value:" + map.get(key));
            entity.addPart(key, new StringBody(map.get(key), Charset.forName("UTF-8")));
        }
        if (StringUtils.isNotEmpty(filePath)) {
            FileBody fileBody = new FileBody(new File(filePath));
            entity.addPart(fileParamsName, fileBody);
        }
        httppost.setEntity(entity);

        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entitys = response.getEntity();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entitys.getContent(),Charset.forName("UTF-8")));
            line = reader.readLine();
            logger.info("=======>>line" + line);
        } else {
            HttpEntity r_entity = response.getEntity();
            line = EntityUtils.toString(r_entity);
            logger.info("错误码是:" + response.getStatusLine().getStatusCode() + "  "
                    + response.getStatusLine().getReasonPhrase());
            logger.info("出错原因是:" + line);
            // 你需要根据出错的原因判断错误信息,并修改
        }
        httpclient.getConnectionManager().shutdown();
        return line;
    }
    
    public static String postStFile(Map<String, String> map) throws ClientProtocolException, IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        String line = "";
        HttpClient httpclient = new DefaultHttpClient();

        HttpPost post = new HttpPost(map.get("url"));
        StringBody apiId = new StringBody(map.get("api_id"));
        StringBody apiSecret = new StringBody(map.get("api_secret"), Charset.forName("UTF-8"));
        FileBody fileBody = new FileBody(new File(map.get("file")));
        MultipartEntity entity = new MultipartEntity();

        entity.addPart("file", fileBody);
        entity.addPart("api_id", apiId);
        entity.addPart("api_secret", apiSecret);
        post.setEntity(entity);
        try {
            HttpResponse response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entitys = response.getEntity();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(entitys.getContent(), Charset.forName("UTF-8")));
                line = reader.readLine();
                logger.info("=======>>line" + line);
            } else {
                HttpEntity r_entity = response.getEntity();
                line = EntityUtils.toString(r_entity);
                logger.info("错误码是:" + response.getStatusLine().getStatusCode() + "  "
                        + response.getStatusLine().getReasonPhrase());
                logger.info("出错原因是:" + line);
                // 你需要根据出错的原因判断错误信息,并修改
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("============>>>>请求" + e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return line;
    }

    public static String postStFile2(Map<String, String> map) throws ClientProtocolException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(map.get("url"));
        FileBody fileBody = new FileBody(new File(map.get("image_file")));
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("image_file", fileBody);
        post.setEntity(entity);
        try {
            post.setHeader("Authorization",genHeaderParam(map.get("api_id"),map.get("api_secret")));
        } catch (SignatureException e1) {
            e1.printStackTrace();
        }// 请将AUTHORIZATION替换为根据API_KEY和API_SECRET得到的签名认证串
        String line = "";
        try {
            HttpResponse response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entitys = response.getEntity();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(entitys.getContent(), Charset.forName("UTF-8")));
                line = reader.readLine();
                logger.info("=======>>line" + line);
            } else {
                HttpEntity r_entity = response.getEntity();
                line = EntityUtils.toString(r_entity);
                logger.info("错误码是:" + response.getStatusLine().getStatusCode() + "  "
                        + response.getStatusLine().getReasonPhrase());
                logger.info("出错原因是:" + line);
                // 你需要根据出错的原因判断错误信息,并修改
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("============>>>>请求" + e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return line;
    }

    public static String genHeaderParam(String api_key, String api_secret) throws SignatureException {

        String GenOriString = genOriString(api_key);
        String EncryptedString = genEncryptString(GenOriString, api_secret);

        String HeaderParam = "key=" + api_key + ",timestamp=" + timestamp + ",nonce=" + nonce + ",signature="
                + EncryptedString;
        System.out.println(HeaderParam);
        return HeaderParam;
    }

    public static String genOriString(String api_key) {

        ArrayList<String> beforesort = new ArrayList<String>();
        beforesort.add(api_key);
        beforesort.add(timestamp);
        beforesort.add(nonce);

        Collections.sort(beforesort, new SpellComparator());
        StringBuffer aftersort = new StringBuffer();
        for (int i = 0; i < beforesort.size(); i++) {
            aftersort.append(beforesort.get(i));
        }

        String OriString = aftersort.toString();
        return OriString;
    }

    public static String genEncryptString(String genOriString, String api_secret) throws SignatureException {
        try {
            Key sk = new SecretKeySpec(api_secret.getBytes(), "HmacSHA256");
            Mac mac = Mac.getInstance(sk.getAlgorithm());
            mac.init(sk);
            final byte[] hmac = mac.doFinal(genOriString.getBytes());
            StringBuilder sb = new StringBuilder(hmac.length * 2);

            @SuppressWarnings("resource")
            Formatter formatter = new Formatter(sb);
            for (byte b : hmac) {
                formatter.format("%02x", b);
            }
            String EncryptedString = sb.toString();
            return EncryptedString;
        } catch (NoSuchAlgorithmException e1) {
            throw new SignatureException("error building signature, no such algorithm in device " + HASH_ALGORITHM);
        } catch (InvalidKeyException e) {
            throw new SignatureException("error building signature, invalid key " + HASH_ALGORITHM);
        }
    }
    public static String httpPost(String postUrl, Map<String,Object> map)
            throws ClientProtocolException, IOException {
        String line = "";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(postUrl);
/*        StringBody api_key = new StringBody(map.get("api_key").toString());
        StringBody secret = new StringBody(map.get("api_secret").toString());
        StringBody reqno = new StringBody(map.get("reqno").toString());
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("api_key", api_key);
        entity.addPart("api_secret", secret);
        entity.addPart("biz_no", reqno);*/
        MultipartEntity entity = new MultipartEntity();
        for (String key : map.keySet()) {
            logger.info("key:" + key + "-------value:" + map.get(key));
            entity.addPart(key, new StringBody(map.get(key).toString(), Charset.forName("UTF-8")));
        }
        
        post.setEntity(entity);
        try {
            HttpResponse response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entitys = response.getEntity();
                BufferedReader reader = new BufferedReader(new InputStreamReader(entitys.getContent()));
                line = reader.readLine();
                logger.info("=======>>line" + line);
            } else {
                HttpEntity r_entity = response.getEntity();
                line = EntityUtils.toString(r_entity);
                logger.info("错误码是:" + response.getStatusLine().getStatusCode() + "  "
                        + response.getStatusLine().getReasonPhrase());
                logger.info("出错原因是:" + line);
                // 你需要根据出错的原因判断错误信息,并修改
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("============>>>>请求" + e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return line;
    }
}

猜你喜欢

转载自blog.csdn.net/shshjj/article/details/80382900