java.net.URLConnectioin的http(get,post)请求(原生)

使用Java发送这两种请求的代码大同小异,只是一些参数设置的不同。步骤如下:

通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
设置请求的参数
发送请求
以输入流的形式获取返回内容
关闭输入流

Get

package com.test.httprequestdemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpGetRequest {

    /**
     * Main
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        System.out.println(doGet());
    }

    /**
     * Get Request
     * @return
     * @throws Exception
     */
    public static String doGet() throws Exception {
        URL localURL = new URL("http://localhost:8080/test/");
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        if (httpURLConnection.getResponseCode() >= 300) {
            throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }

        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }

        } finally {

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }

        return resultBuffer.toString();
    }

}

Post

package com.test.httprequestdemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpPostRequest {

    /**
     * Main
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        System.out.println(doPost());
    }

    /**
     * Post Request
     * @return
     * @throws Exception
     */
    public static String doPost() throws Exception {
        String parameterData = "username=test";

        URL localURL = new URL("http://localhost:8080/test/");
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        try {
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);

            outputStreamWriter.write(parameterData.toString());
            outputStreamWriter.flush();

            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }

        } finally {

            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }

            if (outputStream != null) {
                outputStream.close();
            }

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }

        return resultBuffer.toString();
    }

}

封装好的案例

package com.test.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class HttpRequestor {
    private static final Logger logger = Logger.getLogger(HttpRequestor.class);

    public static void main(String[] args) throws Exception {
    }

    private static Integer connectTimeout = null;
    private static Integer socketTimeout = null;
    private static String proxyHost = null;
    private static Integer proxyPort = null;

    /**
     * Do GET request
     * @param url
     * @param charset:(默认)utf-8
     * @param contentType:(默认)application/x-www-form-urlencoded
     * @return
     * @throws Exception
     * @throws IOException
     */
    public static String doGet(String url,String charset,String contentType)  {
        if(StringUtils.isBlank(url)) return null;
        if(StringUtils.isBlank(charset)) charset="utf-8";
        if(StringUtils.isBlank(contentType)) contentType = "application/x-www-form-urlencoded";
        logger.info("-------start-------request.get.http:"+url);

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            URL localURL = new URL(url);
            URLConnection connection = openConnection(localURL);
            HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
            httpURLConnection.setRequestProperty("Accept-Charset", charset);
            httpURLConnection.setRequestProperty("Content-Type",contentType);
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }
             inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);

                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                }
        } catch (Exception e) {
           e.printStackTrace();
        } finally {

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        logger.info("------end--------request.get");
        return resultBuffer.toString();
    }

    /**
     * Do POST request
     * @param url
     * @param parameterMap
     * @param charset:(默认)utf-8
     * @param contentType:(默认)application/x-www-form-urlencoded
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String,String> parameterMap,String charset,String contentType) {
        if(StringUtils.isBlank(charset)) charset="utf-8";
        if(StringUtils.isBlank(contentType)) contentType = "application/x-www-form-urlencoded";
        logger.info("-------start-------request.post.http:"+url+"?"+parameterMap.toString());

        StringBuffer parameterBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator<String> iterator = parameterMap.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = iterator.next();
                value = parameterMap.get(key);
                parameterBuffer.append(key).append("=").append(value==null?"":value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            URL localURL = new URL(url);
            URLConnection connection = openConnection(localURL);
            HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Accept-Charset", charset);
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(parameterBuffer.toString());
            outputStreamWriter.flush();

            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {

            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        logger.info("------end--------request.post");
        return resultBuffer.toString();
    }

    private static URLConnection openConnection(URL localURL) throws IOException {
        URLConnection connection;
        if (proxyHost != null && proxyPort != null) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = localURL.openConnection(proxy);
        } else {
            connection = localURL.openConnection();
        }
        renderRequest(connection);
        return connection;
    }

    /**
     * Render request according setting
     * @param request
     */
    private static void renderRequest(URLConnection connection) {

        if (connectTimeout != null) {
            connection.setConnectTimeout(connectTimeout);
        }

        if (socketTimeout != null) {
            connection.setReadTimeout(socketTimeout);
        }

    }

    /*
     * Getter & Setter
     */
    public Integer getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        HttpRequestor.connectTimeout = connectTimeout;
    }

    public Integer getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(Integer socketTimeout) {
        HttpRequestor.socketTimeout = socketTimeout;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String proxyHost) {
        HttpRequestor.proxyHost = proxyHost;
    }

    public Integer getProxyPort() {
        return proxyPort;
    }

    public void setProxyPort(Integer proxyPort) {
        HttpRequestor.proxyPort = proxyPort;
    }

}
时间: 2025-01-05 15:51:31

java.net.URLConnectioin的http(get,post)请求(原生)的相关文章

java给微信发送get和post请求

现在做微信订阅号.微信公众号,微信企业号都需要开发者给微信服务器发送get或post请求.具体发送get或post请求源码如下: package com.ciji.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URL

【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法

Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求 4.以输入流的形式获取返回内容 5.关闭输入流 封装请求类 1 package com.util; 2 3 import java.io.BufferedReader; 4 import java.io.IOExcept

用JAVA发送一个XML格式的HTTP请求

1 import java.io.BufferedInputStream; 2 import java.io.BufferedReader; 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStreamWriter; 8 impo

java发送http的get、post请求

文章转载于:http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html Http请求类 package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.

Java:使用HttpClient进行POST和GET请求以及文件下载

1.HttpClient 大家可以先看一下HttpClient的介绍,这篇博文写的还算不错:http://blog.csdn.net/wangpeng047/article/details/19624529 当然,详细的文档,你可以去官方网站查看和下载:http://hc.apache.org/httpclient-3.x/ 2.本博客简单介绍一下POST和GET以及文件下载的应用. 代码如下: package net.mobctrl; import java.io.ByteArrayOutpu

java后台调用HttpURLConnection类模拟浏览器请求(一般用于接口调用)

项目开发中难免遇到外部接口的调用,小生今天初次接触该类,跟着API方法走了一遍,如有不对的地方,还请哆哆指正,拜谢! 1 package com.cplatform.movie.back.test; 2 3 import java.io.BufferedReader; 4 import java.io.DataOutputStream; 5 import java.io.InputStreamReader; 6 import java.net.HttpURLConnection; 7 impor

(转)java代码发送JSON格式的httpPOST请求

import Java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; impor

【Java】向一个页面发送post请求并获取其处理之后的结果与用javascript创建一个表单后提交的安全性

本文对比与<[Java]读取网页中的内容>(点击打开链接)一文,向一个页面发送get请求,并获取其处理之后的结果,这里是向一个页面发送post请求,并获取其处理之后的结果.如果向一个页面发送get请求,并获取其处理之后的结果,只需要直接读取一个网页用?后接各种用&参数连接的参数即可,而向一个页面发送post请求,并获取其处理之后的结果,就不是这么简单了. 这里方法可能在普通的Java文件中不会太常见,但在jsp.安卓等javaweb的网页编程中却十分常用 import java.io.

java发送http的get、post请求[转]

原文链接:http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html package wzh.Http; import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnect