Java URLConnection实现HTTP的GET/POST

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java URLConnection实现HTTP的GET/POST相关的知识,希望对你有一定的参考价值。

public static String doGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            try {in.close();} catch (Exception ex) {}
        	return null;
        }
        try {in.close();} catch (Exception e) {}
        return result;
    }
	
	public static String doPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            try{out.close();}catch(Exception ex){}
            try{in.close();}catch(Exception ex){}
        	return null;
        }
        try{out.close();}catch(Exception ex){}
        try{in.close();}catch(Exception ex){}
        return result;
    }   

 

以上是关于Java URLConnection实现HTTP的GET/POST的主要内容,如果未能解决你的问题,请参考以下文章

Java -- 通过 URLConnection 进行http请求中文乱码

Java Http(s)URLConnection java.io.IOException:服务器返回 HTTP 响应代码:403

查询网页时Java传递URLConnection参数

如何在java中重置URLConnection?

java中的URLConnection如何重用池中的连接

java之URL(URL,URLConnection)实例