Java使用HttpURLConnection发送Get及Post请求简单过程

标准Java接口(java.net) ----HttpURLConnection,可以实现简单的基于URL请求、响应功能;

Get请求:

public String getconnbyget(String url){
        StringBuilder result = new StringBuilder();
		try {
		    //创建地址对象
		    URL u=new URL(url);
			//创建HttpURLConnection链接对象
			HttpURLConnection huconn=(HttpURLConnection) u.openConnection();
            //连接服务器  
            huconn.connect(); 
            // 取得输入流,并使用Reader读取,设定字符编码  
            BufferedReader in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));
            String line;
            //读取返回值,直到为空
            while ((line = in.readLine()) != null) {
            result.append(line);
            }
		} catch (IOException e) {
			e.printStackTrace();
		}
		//关闭输入流
            finally{
            try{
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
		return result.toString();
	}


Post请求:

public String getconnbypost(String url,Map
   
   
    
     headMap){
    StringBuilder result = new StringBuilder();
	try {
			//创建地址对象
			URL u=new URL(url);
			//获取HttpURLConnection链接对象
			HttpURLConnection huconn=(HttpURLConnection) u.openConnection();
			// 发送POST请求必须设置如下两行,如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false
			huconn.setDoOutput(true);
			//如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true
			huconn.setDoInput(true);
			//设置POST方式连接
			huconn.setRequestMethod("POST");
			//创建头信息map迭代器
		    Iterator
    
    
     
      it = headMap.keySet().iterator();
		    //设置请求头配置信息
		    while (it.hasNext()) {
			String key = it.next();
			String value = headMap.get(key);
			huconn.setRequestProperty(key, value);
		}
		//连接服务器  
        OutputStreamWriter out = new OutputStreamWriter(huconn.getOutputStream(),"UTF-8");
        //写入请求体
        out.write(data);
        out.flush();
        out.close();
        // 取得输入流,并使用Reader读取,设定字符编码  
        BufferedReader in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
		} catch (IOException e) {
			e.printStackTrace();
		}
		//关闭输入流
        finally{
            try{
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
		return result.toString();
	}
    
    
   
   

需要导入的jar包
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;






下面是使用 Java 代码编写 HttpURLConnection 发送 GET 和 POST 请求的示例: 1. 发送 GET 请求 ```java import java.net.*; import java.io.*; public class HttpGet { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 2. 发送 POST 请求 ```java import java.net.*; import java.io.*; public class HttpPost { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String input = "{\"username\":\"test\",\"password\":\"test\"}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意,在发送 POST 请求时需要设置 `Content-Type` 和向输出流中写入请求体。如果需要发送其他类型的请求,可以根据需要修改 `setRequestMethod` 和请求头部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值