HttpHelp

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
<span style="white-space:pre">	</span> * @throws Exception  
<span style="white-space:pre">	</span>* @Title: postRequestResponseBodyAsString 
<span style="white-space:pre">	</span>* @Description: http post請求,application/json;charset=UTF-8方式
<span style="white-space:pre">	</span>* @param url
<span style="white-space:pre">	</span>* @param str
<span style="white-space:pre">	</span>* @param contimeout
<span style="white-space:pre">	</span>* @param sotimeout
<span style="white-space:pre">	</span>* @return
<span style="white-space:pre">	</span>* @throws Exception
<span style="white-space:pre">	</span>* @throws 
<span style="white-space:pre">	</span>*/ 
public static String postRequestResponseBodyAsString(String url, String str,Integer contimeout,Integer sotimeout) throws Exception{
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(sotimeout);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(contimeout);
        PostMethod method = new PostMethod(url);
        int statusCode;
        String responseCharSet ="";
        String responseString = "";
        try {
//            String json = JSON.toJSONString(o);
            StringRequestEntity entity = new StringRequestEntity(str,"application/json","utf-8");//解決中文亂碼問題
            method.setRequestEntity(entity);
            method.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
            statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                LOG.error(">>>>>>>>>>>>>> Method failed: " + method.getStatusLine());
                LOG.error(">>>>>>>>>>>>>> Http服務鏈路異常:服務器狀態碼爲" + statusCode);
            }
            responseCharSet = method.getResponseCharSet();
            responseString = method.getResponseBodyAsString();
            if ("ISO-8859-1".equals(responseCharSet)) {
                responseString = new String(responseString.getBytes(responseCharSet), "UTF-8");
            }


        } catch (Exception e) {
            LOG.error(">>>>>>>>>>>>>>  Http服務鏈路異常:" + e.getMessage() + e);
        } finally {
            method.releaseConnection();
        }
        return responseString;
    }
<span style="white-space:pre">	</span>public static String postRequestResponseBodyAsString(String url, Map<String, String> parameters) throws Exception {
<span style="white-space:pre">		</span>return postRequestResponseBodyAsString(url, parameters, 8000, 20000);
<span style="white-space:pre">	</span>}
 /** 
    * @Title: uploadFile 
    * @Description: 上傳文件
    * @param file 文件
    * @param url 上傳地址
    * @param map header-type
    * @return
    * @throws 
    */ 
    public static String uploadFile(File file, String url,Map<String, String> map) {
        if (!file.exists()) {
            return null;
        }
        PostMethod postMethod = new PostMethod(url);
        String responseCharSet ="";
        String responseString = "";
        try {
            // FilePart:用來上傳文件的類
            FilePart fp = new CustomFilePart("filedata", file);
            Part[] parts = { fp };
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,FilePart.DEFAULT_CHARSET); 
            // 對於MIME類型的請求,httpclient建議全用MulitPartRequestEntity進行包裝
            MultipartRequestEntity mre = new MultipartRequestEntity(parts,
                    postMethod.getParams());
            postMethod.setRequestEntity(mre);
            for (String key : map.keySet()) {
                postMethod.addRequestHeader(key, map.get(key));
            }
             
            HttpClient httpClient = new HttpClient();
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(20000);
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
            int status = httpClient.executeMethod(postMethod);
            responseCharSet = postMethod.getResponseCharSet();
            responseString = postMethod.getResponseBodyAsString();
            
            if (status == HttpStatus.SC_OK) {
                if ("ISO-8859-1".equals(responseCharSet)) {
                    responseString = new String(responseString.getBytes(responseCharSet), "UTF-8");
                }
            } else {
                LOG.error(">>>>>>>>>>>>>> Method failed: " + postMethod.getStatusLine());
                LOG.error(">>>>>>>>>>>>>> Http服務鏈路異常:服務器狀態碼爲" + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 釋放連接
            postMethod.releaseConnection();
        }
        return responseString;
    }
 /** 
    * @Title: getFile 
    * @Description: 拿到文件內容
    * @param url 地址
    * @param charset 編碼
    * @return
    * @throws 
    */ 
    public static String getFile(String url,Charset charset) {
        return getFile(url, charset,8000,20000);
    }
    public static String getFile(String url,Charset charset,Integer contimeout,Integer sotimeout) {
        GetMethod method = new GetMethod(url);
        String responseCharSet ="";
        String responseString = "";
        try {
            HttpClient httpClient = new HttpClient();
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(sotimeout);
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(contimeout);
            int status = httpClient.executeMethod(method);
            responseCharSet = method.getResponseCharSet();
            responseString = method.getResponseBodyAsString();
            if (status == HttpStatus.SC_OK) {
                if ("ISO-8859-1".equals(responseCharSet)) {
                    responseString = new String(responseString.getBytes(responseCharSet), charset);
                }
            } else {
                LOG.error(">>>>>>>>>>>>>> Method failed: " + method.getStatusLine());
                LOG.error(">>>>>>>>>>>>>> Http服務鏈路異常:服務器狀態碼爲" + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 釋放連接
            method.releaseConnection();
        }
        return responseString;
    }



發佈了38 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章