JavaWeb 发送get请求

时间:2022-06-23 11:24:57
 

JavaWeb 发送get请求

CreationTime--2018年6月20日15点27分

Author:Marydon

1.前提

  通过HttpClient来实现

2.具体实现

  客户端如何发送请求?

  所需jar包:

  commons-httpclient-3.0.jar

  commons-codec-1.9.jar

  commons-logging-1.1.1.jar

  导入

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
/**
* 发送get请求
* @explain
* 1.请求体:get传参没有请求体
* 2.数据格式:直接拼接到url后面,如:url?key1=value1&key2=value2&...
* @param url 路径及参数
* @return 服务器返回数据
*/
public static String sendGet(String url) {
// 用于接收返回的结果
String resultData = "";
try {
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000); // 设置连接超时
httpClient.getHttpConnectionManager().getParams().setSoTimeout(180000); // 设置读取数据超时
httpClient.getParams().setContentCharset("UTF-8");
GetMethod get = new GetMethod(url);
int status = httpClient.executeMethod(get);
// 状态码为:200
if (status == HttpStatus.SC_OK) {
resultData = get.getResponseBodyAsString();
} else {
throw new RuntimeException("接口连接失败!");
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("接口连接失败!");
}
return resultData;
}

  服务器端如何接收客户端传递的数据?

  request.getParameter("key")

3.客户端调用测试

public static void main(String[] args) {
String requestUrl = "http://localhost:8070/test/rz/server/rzxx/at_VaildToken.do?un_value=B022420184794C7C9D5096CC5F3AE7D2";
// 发送post请求并接收返回结果
String resultData = sendGet(requestUrl);
System.out.println(resultData);
}