java发送get请求参数_get方式请求接受参数的方法

1、获取jsp页面的url,然后通过js获取参数

function getQueryString(name)

{

var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");

var r = parent.document.location.search.substr(1).match(reg);

if(r!=null)return unescape(r[2]); return null;

}

2、通过下面jsp的内置标签获取

3、发起请求在后台接受:

发起请求并返回页面

请求的url:http://localhost:8088/ebtp/appFind/getMyTripFindView?travelNum=00001

public String getMyTripExpenseView( String travelNum,Model model){

model.addAttribute("travelPlan", travelPlan);

model.addAttribute("passKey", PassKeyUtils.getPassKey(travelNum));

return "/ui/sc/ebtp/app/myTrip/expenseView";

只返回数据有三种方法:

方式一:使用getParameter

public String getUrlParam(HttpServletRequest request){

String id = request.getParameter("travelNum");

return id ;

}

方式二:直接使用参数

@RequestMapping(method = RequestMethod.GET, value = "/getMyTripFindView")

public String getMyTripFindView(

HttpServletRequest request, HttpServletResponse response,

String travelNum){

System.out.println("dologin : " + travelNum+ ");

return travelNum;

}

方式三:使用RequestParam注解

@RequestMapping("/getMyTripFindView")

public String getMyTripFindView(

@RequestParam(required=false, defaultValue="001") String travelNum){

return travelNum;

}

注意

当required为true时。表示此参数是必需的,因此必需有值。如果此时把defaultValue去掉,在url中不写此参数,访问时就会报错

Java发送GET请求并设置请求参数通常会使用`HttpURLConnection`或第三方库如`Apache HttpClient`或`OkHttp`。这里以`HttpURLConnection`为例说明: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class GetRequestExample { public static void main(String[] args) throws Exception { // 创建URL对象,代表你要访问的资源 URL url = new URL("http://example.com/api?param=value"); // 获取连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为GET connection.setRequestMethod("GET"); // 设置请求头,这里的"Content-Type"和"Authorization"可以根据需要调整 connection.setRequestProperty("Content-Type", "application/json"); // 如果有JSON数据 connection.setRequestProperty("Authorization", "Bearer your_token"); // 若需要身份验证 // 连接服务器 connection.connect(); // 读取响应状态码 int responseCode = connection.getResponseCode(); System.out.println("Response Code : " + responseCode); // 从服务器读取响应 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印响应内容 System.out.println(response.toString()); // 关闭连接 connection.disconnect(); } } ``` 在这个例子中,通过设置`setRequestProperty`方法,你可以添加任意的请求头信息。记得将`your_token`替换为你实际需要的令牌。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值