http请求工具类

原创 2016年08月31日 10:48:57
package cc.com.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.io.IOUtils;


public class HttpServiceCaller {
	
	/**
	 * @param requestURL
	 * @param data
	 * @return responseText
	 * @throws Exception
	 */
	public static String postMethod(String requestURL, NameValuePair[] data) throws Exception {
		PostMethod postMethod = new PostMethod(requestURL);
		postMethod.setRequestBody(data);

		return call(requestURL, postMethod);
	}

	/**
	 * @param requestURL
	 * @param data
	 * @return responseText
	 * @throws Exception
	 */
	public static String postUTF8Method(String requestURL, NameValuePair[] data) throws Exception {
		PostMethod postMethod = new PostMethod(requestURL);
		postMethod.setRequestBody(data);
		postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		postMethod.addRequestHeader("Connection", "close");
		return call(requestURL, postMethod);
	}

	/**
	 * @author jackzhou
	 * @param requestURL
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String postMethod(String requestURL, HashMap<String, String> postDate) throws Exception {

		NameValuePair[] data = new NameValuePair[postDate.entrySet().size()];
		int i=0;
		for(Map.Entry<String, String> entry : postDate.entrySet()) {
			data[i] = new NameValuePair(entry.getKey(), entry.getValue());
			i++;
        }

		PostMethod postMethod = new PostMethod(requestURL);
		postMethod.setRequestBody(data);
		postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

		HttpClient httpClient = new HttpClient();
		String responseText = null;

		int statusCode = httpClient.executeMethod(postMethod);

		if (statusCode != 200) {
			String errorMessage = IOUtils.toString(postMethod.getResponseBodyAsStream(), postMethod.getResponseCharSet());
			throw new Exception("call failed : " + errorMessage);
		}
		responseText = IOUtils.toString(postMethod.getResponseBodyAsStream(), postMethod.getResponseCharSet());

		return responseText;
	}

        public static String postMethod(String requestURL, HashMap<String, String> postDate, String encode) throws Exception {
		NameValuePair[] data = new NameValuePair[postDate.entrySet().size()];
		int i=0;
		for(Map.Entry<String, String> entry : postDate.entrySet()) {
			data[i] = new NameValuePair(entry.getKey(), entry.getValue());
			i++;
        }

		PostMethod postMethod = new PostMethod(requestURL);
		postMethod.setRequestBody(data);
		postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

		HttpClient httpClient = new HttpClient();
		String responseText = null;

		int statusCode = httpClient.executeMethod(postMethod);

		if (statusCode != 200) {
			String errorMessage = IOUtils.toString(postMethod.getResponseBodyAsStream(), encode);
			throw new Exception("call failed : " + errorMessage);
		}
		responseText = IOUtils.toString(postMethod.getResponseBodyAsStream(), encode);

		return responseText;
	}

	/**
	 * @param requestURL
	 * @return responseText
	 * @throws Exception
	 */
	public static String getMethod(String requestURL) throws Exception {
		GetMethod getMethod = new GetMethod(requestURL);

		return call(requestURL, getMethod);
	}

	/**
	 * @param requestURL
	 * @param method
	 * @return responseText
	 * @throws Exception
	 */
	private static String call(String requestURL, HttpMethod method) throws Exception {
		HttpClient httpClient = new HttpClient();

		//会报错 HTTP 503 special method ....
//		method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//		method.addRequestHeader("Connection", "close");

		String responseText = null;
		try {
			int statusCode = httpClient.executeMethod(method);

			if (statusCode != 200) {
				String errorMessage = method.getResponseBodyAsString();
				throw new Exception("call failed : " + errorMessage);
			}


			StringBuilder responseBody = new StringBuilder();
	        InputStream is = method.getResponseBodyAsStream();
	        BufferedReader br = new BufferedReader(new InputStreamReader(is));

	        String line;
	        while((line = br.readLine())!=null) {
	        	responseBody.append(line);
	        }

	        responseText = responseBody.toString();

	        br.close();
	        is.close();
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				SimpleHttpConnectionManager connectionManager = (SimpleHttpConnectionManager) httpClient.getHttpConnectionManager();
				connectionManager.shutdown();
				method.releaseConnection();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}

        return responseText;
	}
	
	/**
	 * @param requestURL
	 * @return responseText
	 * @throws Exception
	 */
	public static String getMethod2(String requestURL) throws Exception {
		GetMethod getMethod = new GetMethod(requestURL);

		return call2(requestURL, getMethod);
	}
	
	/**
	 * @param requestURL
	 * @param method
	 * @return responseText
	 * @throws Exception
	 */
	private static String call2(String requestURL, HttpMethod method) throws Exception {
		HttpClient httpClient = new HttpClient();

		//会报错 HTTP 503 special method ....
//		method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//		method.addRequestHeader("Connection", "close");

		String responseText = null;
		try {
			int statusCode = httpClient.executeMethod(method);

			if (statusCode != 200) {
				String errorMessage = method.getResponseBodyAsString();
				throw new Exception("call failed : " + errorMessage);
			}


		/*	StringBuilder responseBody = new StringBuilder();
	        InputStream is = method.getResponseBodyAsStream();
	        BufferedReader br = new BufferedReader(new InputStreamReader(is));

	        String line;
	        while((line = br.readLine())!=null) {
	        	responseBody.append(line);
	        }*/

	        responseText = method.getResponseBodyAsString();

	       // br.close();
	     //   is.close();
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				SimpleHttpConnectionManager connectionManager = (SimpleHttpConnectionManager) httpClient.getHttpConnectionManager();
				connectionManager.shutdown();
				method.releaseConnection();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}

        return responseText;
	}
	public static String putMethod(String requestURL, HashMap<String, String> postDate) throws Exception {

		NameValuePair[] data = new NameValuePair[postDate.entrySet().size()];
		int i=0;
		for(Map.Entry<String, String> entry : postDate.entrySet()) {
			data[i] = new NameValuePair(entry.getKey(), entry.getValue());
			i++;
        }

		PutMethod putMethod = new PutMethod(requestURL);
		putMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
//		method.addRequestHeader("Connection", "close");
		
		new StringReader("");
		//RequestEntity entity =new StringRequestEntity(JSONObject.fromObject(postDate).toString());;
		String str=JSONObject.fromObject(postDate).toString();
		RequestEntity entity =new InputStreamRequestEntity( new ByteArrayInputStream(str.getBytes()));
		putMethod.setRequestEntity(entity);
		HttpClient httpClient = new HttpClient();
		String responseText = null;

		int statusCode = httpClient.executeMethod(putMethod);
		System.out.println("http code:"+statusCode);

		if (statusCode <200 || statusCode>399) {
			String errorMessage = IOUtils.toString(putMethod.getResponseBodyAsStream(), putMethod.getResponseCharSet());
			System.out.println("errorMsg:"+errorMessage);
			throw new Exception("call failed : " + errorMessage);
		}
		responseText = IOUtils.toString(putMethod.getResponseBodyAsStream(), putMethod.getResponseCharSet());

		return responseText;
	}
	
	public static String postStringMethod(String requestURL,String postData) throws Exception {

		PostMethod putMethod = new PostMethod(requestURL);
		putMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");

		RequestEntity entity =new InputStreamRequestEntity( new ByteArrayInputStream(postData.getBytes()));
		putMethod.setRequestEntity(entity);
		HttpClient httpClient = new HttpClient();
		String responseText = null;

		int statusCode = httpClient.executeMethod(putMethod);
		System.out.println("http code:"+statusCode);

		if (statusCode <200 || statusCode>399) {
			String errorMessage = IOUtils.toString(putMethod.getResponseBodyAsStream(), putMethod.getResponseCharSet());
			System.out.println("errorMsg:"+errorMessage);
			throw new Exception("call failed : " + errorMessage);
		}
		responseText = IOUtils.toString(putMethod.getResponseBodyAsStream(), putMethod.getResponseCharSet());

		return responseText;
	}


}

java HTTPClient PostMethod 中文乱码问题解决方法

项目中发现使用HTTPClient的PostMethod方法有乱码,尝试使用     1. postMethod.getParams().setParameter(HttpMethodP...
  • Zhaky
  • Zhaky
  • 2016年03月15日 17:40
  • 1987

Java工具类--通过HttpClient发送http请求

在写网络程序的时候,经常会有从网址获取数据的需求,上一篇解析JSON就需要从百度获取天气数据,本文介绍一种模拟发送http请求的工具–HttpClient。HttpClient的介绍 The mo...
  • frankcheng5143
  • frankcheng5143
  • 2015年11月27日 15:17
  • 16037

Http请求工具类

HttpUtil.java package com.jrbac.util; import java.io.File; import java.io.IOException; import java....
  • tianya3530
  • tianya3530
  • 2017年08月17日 17:41
  • 814

HTTP请求工具类(Java)

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
  • qduningning
  • qduningning
  • 2013年04月28日 16:54
  • 12841

httpclient 工具类(更新 支持json 和xml)

package com.xyh.util; import java.io.IOException; import java.io.InputStream; import java.io.Unsup...
  • hustxiayu
  • hustxiayu
  • 2018年01月10日 16:27
  • 70

Http请求工具类 httputil

package com.snowfigure.kits.net;import java.io.BufferedReader; import java.io.IOException; import ...
  • Working_Harder
  • Working_Harder
  • 2015年10月16日 13:20
  • 11017

四、java项目常用工具类之http请求工具类

一、问题描述及试用场景: 在项目开发中,经常用调用http接口,下面是封装apache的httpclient工具类。 二、样例代码: package org.egg.utils; im...
  • hupoling
  • hupoling
  • 2017年11月12日 16:22
  • 681

http请求工具类

  • 2017年10月07日 15:29
  • 3KB
  • 下载

轻松把玩HttpClient之封装HttpClient工具类(一)(现有网上分享中的最强大的工具类)

搜了一下网络上别人封装的HttpClient,大部分特别简单,有一些看起来比较高级,但是用起来都不怎么好用。调用关系不清楚,结构有点混乱。所以也就萌生了自己封装HttpClient工具类的想法。要做就...
  • xiaoxian8023
  • xiaoxian8023
  • 2015年11月19日 11:20
  • 27142

HttpClient4.3 post与get请求工具类完整示例

整个工具类代码如下所示,可直接使用! import java.io.IOException; import org.apache.http.HttpEntity; import org.apache...
  • lupangdelu
  • lupangdelu
  • 2016年03月29日 17:42
  • 6728
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:http请求工具类
举报原因:
原因补充:

(最多只允许输入30个字)