发送 GET 和 POST请求

本文介绍了如何使用Java实现HTTP GET和POST请求的方法,包括设置请求头、发送请求参数及处理响应数据等关键步骤。

/**
	 *@param url 发送请求的url
	 *@param param 请求参数 请求参数应该是 name=xx&pass=xxxx 
	 */
	public static String sendGet(String url,String param){
		String result="";
		BufferedReader bfr=null;
		try {
			String urlName=url+"?"+param;
			URL realUrl=new URL(urlName);
			URLConnection conn=realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-age", "Mozilla/4.0 (compatible;MSIE 6.0;Window NT 5.1;SV1)");
			
			//建立实际的连接
			conn.connect();
			Map<String,List<String>> map=conn.getHeaderFields();
			//遍历所有的响应头字段
			for (String key: map.keySet()) {
				System.out.println(key+"--->"+map.get(key));
			}
			//定义 BufferedRead输入流来读取URL的响应
			bfr=new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			String line;
			while((line=bfr.readLine())!=null){
				result+="\n"+line;
			}
		} catch (Exception e) {
			System.out.print("发送GET请求出现异常:"+e);
			e.printStackTrace();
		}finally{
			try {
				if(bfr!=null)
					bfr.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
		
	}
	
	/**
	 *@param url 发送请求的url
	 *@param param 请求参数 请求参数应该是 name=xx&pass=xxxx 
	 */
	public static String sendPost(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-age", "Mozilla/4.0 (compatible;MSIE 6.0;Window NT 5.1;SV1)");
			
			//发送POST请求必须设置如下两行
			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+="\n"+line;
			}
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常:"+e);
			e.printStackTrace();
		}finally{
			try {
				if(out!=null)
					out.close();
				if(in!=null)
					in.close();
				
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	


Get 发送 数据

public String getJosnByUrl(String url) {
		StringBuffer josn = new StringBuffer();
		BufferedReader reader = null;
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;
		try {
			URL httpUrl = new URL(url);
			URLConnection connection = httpUrl.openConnection();
			httpURLConnection = (HttpURLConnection) connection;
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setReadTimeout(30000);// 无响应30秒,断开会话
			httpURLConnection.setConnectTimeout(30000);
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setRequestProperty("Referer","http://taobao.51bi.com");
			httpURLConnection.setRequestProperty("Accept-Language","zh-cn");
			httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)");
			httpURLConnection.connect();
			inputStream = httpURLConnection.getInputStream();// 发送连接
			reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				josn.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(reader != null)
					reader.close();
				if(inputStream != null)
					inputStream.close();
				if(httpURLConnection != null)
					httpURLConnection.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return josn.toString().trim();
	}




post 发送数据xml 或者json 然后读取返回值

public String getJosnByUrl(String url,String param) {
		StringBuffer josn = new StringBuffer();
		BufferedReader reader = null;
		PrintWriter out=null;
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;
		try {
			URL httpUrl = new URL(url);
			URLConnection connection = httpUrl.openConnection();
			httpURLConnection = (HttpURLConnection) connection;
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setReadTimeout(30000);// 无响应30秒,断开会话
			httpURLConnection.setConnectTimeout(30000);
			httpURLConnection.setRequestMethod("POST");
			
			//httpURLConnection.setRequestProperty("Referer","http://taobao.51bi.com");
			httpURLConnection.setRequestProperty("Accept-Language","zh-cn");
			httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)");
			httpURLConnection.connect();
			out=new PrintWriter(httpURLConnection.getOutputStream());
			out.write(param);//数据写入缓存中
			out.flush();
			inputStream = httpURLConnection.getInputStream();// 发送连接
		
			reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				josn.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(out!=null)
					out.close();
				if(reader != null)
					reader.close();
				if(inputStream != null)
					inputStream.close();
				if(httpURLConnection != null)
					httpURLConnection.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return josn.toString().trim();
	}
在VSCode中编写代码发送GETPOST请求可以使用不同的编程语言库来实现,以下分别给出JavaVue的示例。 ### Java示例 在Java里,可借助Servlet来处理GETPOST请求。下面是一个示例代码,该代码会让GET请求的响应文本显示为绿色,POST请求的响应文本显示为红色: ```java public class RequestMethodServlet extends HttpServlet{ //处理get请求 public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException { String name=request.getParameter("name"); response.getWriter().println("<h1 style='color:green'>"+name+"</h1>"); } //处理post请求 public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException { String name=request.getParameter("name"); response.getWriter().println("<h1 style='color:red'>"+name+"</h1>"); } } ``` 此代码定义了一个继承自`HttpServlet`的`RequestMethodServlet`类,在`doGet`方法中处理GET请求,在`doPost`方法中处理POST请求,并通过设置不同的样式颜色来区分响应内容[^1]。 ### Vue示例 在Vue项目中可以使用`vue-resource`库发送GETPOST请求。以下是一个发送GET请求的示例: ```javascript methods: { getInfo() { // vue-resource发送get请求 this.$http.get('https://api.apiopen.top/api/getHaoKanVideo?page=0&size=2').then(function (data) { //data参数就是服务器接口返回给客户端的数据:json console.log(data); // 拿到服务器返回的成功的数据 }) } } ``` 该代码在`methods`对象中定义了一个`getInfo`方法,使用`this.$http.get`方法发送GET请求,并通过`then`方法处理服务器返回的数据[^2]。 ### 使用VSCode测试接口 若要使用VSCode测试接口,可按以下步骤操作: 1. 写入测试接口,例如测试取消订单接口: ```plaintext @Content-Type = application/json ### 测试取消订单接口 POST http://10.233.x.x:8080/test-adapter/testCancelOrder Content-Type: {{Content-Type}} { "warehouseCode":"OTHER", "orderCode":"22", "orderType":"TK" } ``` 2. 发送请求,测试接口(点击`Send Request`或者右键选择`Send Request`)[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值