import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class post3 {
/**
* 2023年2月14日20:36:21
* POST请求示例,练习
* 博客地址如下:
* https://blog.csdn.net/TiankkTT/article/details/126685422?ops_request_misc=&request_id=&biz_id=102&utm_term=HttpURLConnection&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-4-126685422.nonecase&spm=1018.2226.3001.4187
*/
public static void main(String[] args) {
try {
// 1. 获取访问地址URL
URL url = new URL("http://192.168.2.7:8080/j_spring_security_check");
// 2. 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
/* 3. 设置请求参数等 */
// 请求方式
connection.setRequestMethod("POST");
// 设置连接超时时间(以毫秒为单位)
connection.setConnectTimeout(3000);
// 设置是否向 HttpUrlConnection 输出,对于post请求,参数要放在 http 正文内,因此需要设为true,默认为false。
connection.setDoOutput(true);
// 设置是否从 HttpUrlConnection读入,默认为true
connection.setDoInput(true);
// 设置是否使用缓存
connection.setUseCaches(false);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(true);
// 设置使用标准编码格式编码参数的名-值对
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 添加 HTTP HEAD 中的一些参数。JDK8中,HttpURLConnection默认开启Keep-Alive
// connection.setRequestProperty("Connection", "Keep-Alive");
// 连接
try {
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
/* 4. 处理输入输出 */
// 写入参数到请求中
String params = "j_username=admin&j_password=admin&from=%2Fjob%2Ftest%2F&Submit=%E7%99%BB%E5%BD%95";
OutputStream out = connection.getOutputStream();
out.write(params.getBytes());
out.flush();
out.close();
// 从连接中读取响应信息
StringBuilder msg = new StringBuilder();
int code = connection.getResponseCode();
if (code == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
msg.append(line).append("\n");
}
reader.close();
}
// 5. 断开连接
connection.disconnect();
// 处理结果
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
说明:本地搭建Jenkins,验证登录接口
问题:设置登录接口的参数如下,可以正常使用:
String params = "j_username=admin&j_password=admin&from=%2Fjob%2Ftest%2F&Submit=%E7%99%BB%E5%BD%95";
但是使用JSONObject提交数据的时候为什么提交不上去?
JSONObject jso = new JSONObject();
jso.put("j_username", "admin");
jso.put("j_password", "admin");
jso.put("from", "");
jso.put("Submit", "%E7%99%BB%E5%BD%95");
jso.put("remember_me", "ON");
out.write(jso.toString().getBytes());