HttpClient doPost doGet 请求 返回内存流

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * http invoker for doPost request or doGet request, return memory stream
 * <code>OutputStream</code>,ie. <code>ByteArrayOutputStream</code>
 * 
 * 
 * @author 
 * @see org.apache.http.client.HttpClient
 */
public class HttpInvoker
{

	/**
	 * doGet方式访问URL
	 * 
	 * @param url
	 * @return OutputStream
	 */
	public static OutputStream doGet(String url)
	{
		HttpClient httpclient = new DefaultHttpClient();
		OutputStream os = null;
		try
		{
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();

			if (entity != null)
			{
				InputStream instream = entity.getContent();
				os = new ByteArrayOutputStream();
				int temp = 0;
				while ((temp = instream.read()) != -1)
				{
					os.write(temp);
				}

				os.flush();
				os.close();
				return os;
			}
		}
		catch (Exception e)
		{
		}
		finally
		{
			httpclient.getConnectionManager().shutdown();
		}
		return null;

	}

	/**
	 * http url request with parameter map
	 * 
	 * @param url server url
	 * @param parameterMap Parameters
	 * @return OutputStream
	 */
	public static OutputStream doPostWithUrlParams(String url,
			Map<String , Object> parameterMap)
	{
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String , Object> element : parameterMap.entrySet())
		{
			nameValuePairs.add(new BasicNameValuePair(element.getKey(), String
					.valueOf(element.getValue())));
		}
		try
		{
			return doPost(url, new UrlEncodedFormEntity(nameValuePairs));
		}
		catch (UnsupportedEncodingException e)
		{
		}
		return null;
	}

	/**
	 * post方式写对象流到服务端
	 * 
	 * @param url server url
	 * @param obj Object
	 * @return OutputStream
	 */
	public static OutputStream doPostWithObject(String url, final Object obj)
	{
		ContentProducer cp = new ContentProducer()
		{
			// 二进制流
			public void writeTo(OutputStream outstream) throws IOException
			{
				ObjectOutputStream oos = new ObjectOutputStream(outstream);
				oos.writeObject(obj);
				oos.flush();
				oos.close();
			}
		};
		return doPost(url, new EntityTemplate(cp));
	}

	/**
	 * 
	 * httpClient 执行post请求 返回 OutputStream对象
	 * 
	 * @param url String
	 * @param entity HttpEntity
	 * @return OutputStream
	 */
	private static OutputStream doPost(String url, HttpEntity entity)
	{
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		OutputStream os = null;
		post.setEntity(entity);
		try
		{
			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();
			InputStream in = resEntity.getContent();

			if (resEntity != null)
			{
				os = new ByteArrayOutputStream();
				int temp = 0;
				while ((temp = in.read()) != -1)
				{
					os.write(temp);
				}
				os.flush();
				os.close();
				EntityUtils.consume(resEntity);
				return os;
			}
		}
		catch (Exception e)
		{
		}
		finally
		{
			client.getConnectionManager().shutdown();
		}
		return null;
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient5是Apache HttpClient的最新版本,它提供了许多新的功能和改进。下面是使用HttpClient5发送POST和GET请求的示例代码: 1.发送POST请求 ```java import org.apache.hc.client5.http.classic.HttpClient; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.StringEntity; import java.io.IOException; public class HttpClientUtils { public static String doPost(String url, String json) { String result = ""; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); try { result = httpClient.execute(httpPost, response -> { HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { return responseEntity.getContent(); } else { return null; } }); } catch (IOException e) { e.printStackTrace(); } return result; } } ``` 2.发送GET请求 ```java import org.apache.hc.client5.http.classic.HttpClient; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.core5.http.HttpEntity; import java.io.IOException; public class HttpClientUtils { public static String doGet(String url) { String result = ""; HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet(url); try { result = httpClient.execute(httpGet, response -> { HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { return responseEntity.getContent(); } else { return null; } }); } catch (IOException e) { e.printStackTrace(); } return result; } } ``` 以上代码中,我们使用HttpClient5创建了一个HttpClient对象,然后使用HttpPost或HttpGet方法创建一个请求对象,设置请求参数并执行请求。在执行请求时,我们使用了Java 8中的Lambda表达式来处理响应数据。最后,我们返回响应的字符串结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值