HTTP表单请求

okHttp 发送表单请求

需要添加依赖

compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.9.0'
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

public class HttpPostExample {
    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();

        // 创建请求体
        RequestBody formBody = new FormBody.Builder()
                .add("arg1", "xxx") // 表单字段1
                .add("arg2", "aaa") // 表单字段2
                .build();

        // 创建请求对象
        Request request = new Request.Builder()
                .url("https://example.com/submit")
                .post(formBody) // 使用POST请求方法
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .addHeader("Connection", "keep-alive")
                .addHeader("Cookie", "xxx")
                .addHeader("Host", "xxx") // 设置请求头,可选
                .build();

        try {
            // 执行请求
            Response response = client.newCall(request).execute();
            // 处理响应
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                System.out.println("Response: " + responseBody);
            } else {
                System.err.println("Request failed: " + response.code() + " " + response.message());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

httpclient 发送表单请求

需要添加依赖

compile 'org.apache.httpcomponents:httpclient:4.3.5'
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import java.net.URLEncoder;

import java.io.IOException;


public class HttpClientExample {
    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 目标 URL
            String apiUrl = "https://example.com/submit";

            // 创建 POST 请求
            HttpPost httpPost = new HttpPost(apiUrl);

            // 自定义请求头
            Header[] headers = {
                    new BasicHeader("Server", "nginx"),
                    new BasicHeader("Host", "example.com"),
                    new BasicHeader("Accept", "*/*"),
                    new BasicHeader("Accept-Encoding", "gzip, deflate, br"),
                    new BasicHeader("Connection", "keep-alive"),
                    new BasicHeader("Cookie", "xxx"),
                    new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
                    )
            };
            httpPost.setHeaders(headers);


            // 构建表单内容
            String formData = "arg1=xxx&args2=xxx";
            // 某些参数需要encode的,则需要
            // String args3 = URLEncoder.encode(args3,"UTF-8");
            // 设置请求体
            StringEntity entity = new StringEntity(formData);
            httpPost.setEntity(entity);

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应实体
                HttpEntity responseEntity = response.getEntity();

                // 打印响应状态码
                System.out.println("Response Code: " + response.getStatusLine().getStatusCode());

                // 打印响应内容
                String responseBody = EntityUtils.toString(responseEntity);
                System.out.println("Response Data: " + responseBody);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java 本身工具包

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class PostRequestExample {
    public static void main(String[] args) {
        try {
            // 目标 URL
            String url = "https://example.com/submit";

            // 创建 URL 对象
            URL apiUrl = new URL(url);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");

            // 设置自定义请求头
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Cookie", "xxx");
            connection.setRequestProperty("Connection", "keep-alive");

            // 启用输入和输出流
            connection.setDoOutput(true);

            // 构建表单内容
            String formData = "arg1=xxx&args2=xxx";
            // 某些参数需要encode的,则需要
            // String args3 = URLEncoder.encode(args3,"UTF-8");

            // 将表单内容写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = formData.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应代码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 输出响应内容
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("Request failed.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

posted @   Eiffelzero  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示