欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

http post 请求

程序员文章站 2022-07-07 22:22:21
...

 

 

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.cmcc.rd.aoi.log.LoggerFactory;
import com.cmcc.rd.aoi.util.DatetimeUtil;

public class HttpPostUtil
{
	/**
	 * 
	 * @param postXML
	 *            放在消息内容体中的字符串
	 * @param url
	 *            要访问的 URL
	 * @return 返回POST请求响应返回的内容体字符串和cookie
	 */
	public static String[] post(String postXML, String url, Map<String, String> map)
	{
		String urlstr = url;
		String servlet_res = null;
		InputStream in = null;
		HttpURLConnection conn = null;
		String setCookie = null;
		try
		{
			LoggerFactory.log("SendTo: " + urlstr);
			URL send_url = new URL(urlstr);

			conn = (HttpURLConnection) send_url.openConnection();
			conn.setConnectTimeout((int) (10 * DatetimeUtil.SECOND));
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
			conn.setRequestMethod("POST");
			for (String key : map.keySet())
				conn.setRequestProperty(key, map.get(key));
			conn.connect();

			OutputStream raw = conn.getOutputStream();
			OutputStream buf = new BufferedOutputStream(raw);
			OutputStreamWriter out = new OutputStreamWriter(buf, "UTF-8");
			System.out.println("inputData = " + postXML);
			out.write(postXML);
			out.flush();
			out.close();

			in = conn.getInputStream();
			setCookie = conn.getHeaderField("Set-Cookie");
			// 采用byte流读取

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] bytes = new byte[1];
			while (in.read(bytes) != -1)
			{
				baos.write(bytes);
			}
			in.close();
			String ouputData = new String(baos.toByteArray());
			LoggerFactory.log("ouputData = " + ouputData);

			servlet_res = ouputData;
		}
		catch (Exception e)
		{
			LoggerFactory.log(e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (in != null)
					in.close();
				if (conn != null)
					conn.disconnect();
			}
			catch (IOException e)
			{
				LoggerFactory.log(e.getMessage());
			}
		}

		return new String[] {servlet_res, setCookie};
	}
	 
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。


http post 请求
            
    
    博客分类: java httppost请求 http post 请求
            
    
    博客分类: java httppost请求 http post 请求
            
    
    博客分类: java httppost请求 
 
 
 谢谢您的赞助,我会做的更好!

 

 

相关标签: http post 请求