java代码发送HTTP Post请求

来源:互联网 发布:常用的外文数据库 编辑:程序博客网 时间:2024/05/23 01:44

代码如下,不用过多解释了吧:

package imscportal.transform.http.channel.impl;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLDecoder;import imscportal.transform.http.channel.spi.IHttpChannel;import imscportal.util.log.LoggerMap;import imscportal.util.log.MyLogger;import imscportal.util.parameter.IMSCParameter;public class HttpChannel implements IHttpChannel {    private MyLogger logger = LoggerMap.getLogger(this.getClass());    private URL url;    public HttpChannel(String url) throws Exception {        this.url = new URL(url);    }    public String sendPostRequest(String content) throws Exception {        logger.debug("try to open http connection to: '" + this.url.getPath()                + ":" + this.url.getPort() + "'");        HttpURLConnection conn = (HttpURLConnection) this.url.openConnection();                conn.setConnectTimeout(IMSCParameter                .getHTTP_POST_REQUEST_CONNECT_TIMEOUT());        conn.setReadTimeout(IMSCParameter.getHTTP_POST_RESPONSE_READ_TIMEOUT());        conn.setDoOutput(true);        conn.setRequestMethod("POST");                logger.debug("try to get output stream");        OutputStream output = conn.getOutputStream();                logger.debug("try to write '" + content + "'");        output.write(content.getBytes());        output.flush();        output.close();                logger.debug("try to get input stream");        BufferedReader reader = new BufferedReader(new InputStreamReader(conn                .getInputStream()));        String line;        StringBuffer buffer = new StringBuffer(IMSCParameter                .getHTTP_POST_RESPONSE_BUFFER_SIZE());                while ((line = reader.readLine()) != null) {            buffer.append(line);        }                String value = buffer.toString();        logger.debug("get resposne: '" + value + "'");                value = URLDecoder.decode(value, IMSCParameter.getINTERNAL_CHARSET());        return value;    }}
0 0
原创粉丝点击