码迷,mamicode.com
首页 > Web开发 > 详细

HttpUtils

时间:2016-08-06 09:47:02      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

 

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
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.params.HttpMethodParams;

public class HttpUtils {

    /**
     * get请求
     * 
     * @param url
     * @return String
     */

    public static String get(String url) {
        String result = null;
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        GetMethod method = new GetMethod(url);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + method.getStatusLine());
            }

            // Read the response body.
            byte[] responseBody = method.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary
            // data
            result = new String(responseBody);

        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     * @param paramMap
     * @return String
     */
    public static String post(String url, Map<String, String> paramMap) {
        String result = null;
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        PostMethod post = new PostMethod(url);

        // Provide custom retry handler is necessary
        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        if (paramMap != null) {
            Iterator<Entry<String, String>> it = paramMap.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, String> entry = it.next();
                post.addParameter(entry.getKey(), entry.getValue());
            }
        }

        try {
            // Execute the method.
            int statusCode = client.executeMethod(post);

            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + post.getStatusLine());
            }

            // Read the response body.
            byte[] responseBody = post.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary
            // data
            result = new String(responseBody);

        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            post.releaseConnection();
        }
        return result;
    }
    
    
    /**
     * 向URL post json
     * 
     * @param url
     * @param jsonStr
     * @return String
     */
    public static String json(String url, String jsonStr) {
        String result = null;
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        PostMethod post = new PostMethod(url);

        // Provide custom retry handler is necessary
        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        
        StringRequestEntity sre = null;
        try {
            sre = new StringRequestEntity(jsonStr, "application/json" , "utf-8");
        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        } 
        post.setRequestEntity(sre);

        try {
            // Execute the method.
            int statusCode = client.executeMethod(post);

            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + post.getStatusLine());
            }

            // Read the response body.
            byte[] responseBody = post.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary
            // data
            result = new String(responseBody);

        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            post.releaseConnection();
        }
        return result;
    }
}

 

HttpUtils

标签:

原文地址:http://www.cnblogs.com/zno2/p/5718500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!