1. 程式人生 > >get,post,delete,put的http請求。

get,post,delete,put的http請求。

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.3</version>

</dependency>

===================================================================

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpClientUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    private static final String ContentEncoding = "UTF-8";
    private static final int SocketTimeout = 5000;

    /**
     httpClient的get請求方式
     * @return
     * @throws Exception
     */
    public static String doGet(String url)   {
        logger.info("==================================doGet=={}",url);
      /*
       * 使用 GetMethod 來訪問一個 URL 對應的網頁,實現步驟:
       * 1:生成一個 HttpClinet 物件並設定相應的引數。
       * 2:生成一個 GetMethod 物件並設定響應的引數。
       * 3:用 HttpClinet 生成的物件來執行 GetMethod 生成的Get方法。
       * 4:處理響應狀態碼。
       * 5:若響應正常,處理 HTTP 響應內容。
       * 6:釋放連線。
       */
      /* 1 生成 HttpClinet 物件並設定引數 */
        HttpClient httpClient = new HttpClient();
        // 設定 Http 連線超時為5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(SocketTimeout);
      /* 2 生成 GetMethod 物件並設定引數 */
        GetMethod getMethod = new GetMethod(url);
        // 設定 get 請求超時為 5 秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, SocketTimeout);
        // 設定請求重試處理,用的是預設的重試處理:請求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
      /* 3 執行 HTTP GET 請求 */
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            logger.info("==================================doGet=={}",statusCode);
         /* 4 判斷訪問的狀態碼 */
            if (statusCode != HttpStatus.SC_OK&&statusCode != HttpStatus.SC_CREATED&&statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("請求出錯: "+ getMethod.getStatusLine());
                return response;
            }
         /* 5 處理 HTTP 響應內容 */
            // HTTP響應頭部資訊,這裡簡單列印
            /*Header[] headers = getMethod.getResponseHeaders();
            for (Header h : headers){
                logger.info(h.getName() + "------------ " + h.getValue());
            }*/
            // 讀取 HTTP 響應內容,這裡簡單列印網頁內容
            byte[] responseBody = getMethod.getResponseBody();// 讀取為位元組陣列
            response = new String(responseBody, ContentEncoding);
            logger.info("----------response:" + response);
            // 讀取為 InputStream,在網頁內容資料量大時候推薦使用
            // InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            // 發生致命的異常,可能是協議不對或者返回的內容有問題
            logger.error("請檢查輸入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // 發生網路異常
            logger.error("發生網路異常!");
            e.printStackTrace();
        } finally {
         /* 6 .釋放連線 */
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * HttpClient PUT請求
     * @author huang
     * @date 2013-4-10
     * @return
     */
    public static String doPut(String uri,String jsonObj){
        logger.info("==================================doPut=={},{}",uri,jsonObj);

        String resStr = "";
        HttpClient htpClient = new HttpClient();
        PutMethod putMethod = new PutMethod(uri);
        putMethod.addRequestHeader( "Content-Type","application/json" );
        putMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, ContentEncoding );
        putMethod.setRequestBody( jsonObj );
        try{
            int statusCode = htpClient.executeMethod( putMethod );
            logger.info("==================================doPut=={}",statusCode);
            if (statusCode != HttpStatus.SC_OK&&statusCode != HttpStatus.SC_CREATED&&statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: "+putMethod.getStatusLine() );
                return resStr;
            }
            byte[] responseBody = putMethod.getResponseBody();
            resStr = new String(responseBody,ContentEncoding);
            logger.info("----------response:" + resStr);
        }catch(Exception e){
            logger.error(" failed: " + e.getMessage());
            e.printStackTrace();
        }finally{
            putMethod.releaseConnection();
        }
        return resStr;
    }

    /**
     * post請求
     * @param url
     * @param jsonObj
     * @return
     */
    public static String doPost(String url,String jsonObj){
        logger.info("==================================doPost=={},{}",url,jsonObj);

        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json; charset=UTF-8");
        String response = "";
        try {
            StringEntity stringEntity = new StringEntity( jsonObj,"UTF-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(stringEntity);
            HttpResponse res = client.execute(post);
            int statusCode=res.getStatusLine().getStatusCode();
            logger.info("==================================doPost=={}",statusCode);
            if (statusCode != HttpStatus.SC_OK&&statusCode != HttpStatus.SC_CREATED&&statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: "+res.getStatusLine() );
                return response;
            }
            response = EntityUtils.toString(res.getEntity());// 返回json格式:
            logger.info("----------response:" + response);
        } catch (Exception e) {
            logger.error(" failed: " + e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    public static String doDelete(String uri)  {
        logger.info("==================================doDelete=={}",uri);

        String data= "";
        HttpClient httpClient= new HttpClient();
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ContentEncoding);
        DeleteMethod method = null;
        try{
            method= new DeleteMethod();
            method.setURI(new URI(uri,false));
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, SocketTimeout);
            int statusCode = httpClient.executeMethod(method);
            logger.info("==================================doDelete=={}",statusCode);
            if (statusCode != HttpStatus.SC_OK&&statusCode != HttpStatus.SC_CREATED&&statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: " + method.getStatusLine());
                return data;
            }
            data= new String(method.getResponseBody(),ContentEncoding);
            logger.info("----------response:" + data);
        }catch(HttpException e){
            e.printStackTrace();
            logger.error("Please check your provided http address!");
        }catch(IOException e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }finally{
            if(method!=null)
                method.releaseConnection();
        }
        return data;
    }


    public static void main(String args[]) {
        /*String url =  "http://*:8082/rest/identity/users";
        Map<String, Object> vars = Maps.newHashMap();
        vars.put("id", "bb");
        vars.put("firstName", "我們是中國人");
        HttpClientUtil.doPost(url, JsonUtil.JSON_Bean2String(vars));*/


        /*String url =  "http://*:8082/rest/identity/users/bb";
        Map<String, Object> vars = Maps.newHashMap();
        vars.put("firstName", "我們是中國人,是   嗎???");
        HttpClientUtil.doPut(url, JsonUtil.JSON_Bean2String(vars));*/
    }
}