首页 > 其他分享 >HTTP请求

HTTP请求

时间:2023-09-19 09:26:22浏览次数:35  
标签:HTTP String org new apache import response 请求

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.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", "JSESSIONID=4030473904CA137E42E741B156BEFF2E-s1"),
                    new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
                    )
            };
            httpPost.setHeaders(headers);


            // 构建表单内容
            String formData = "arg1=xxx&args2=xxx";
            // 设置请求体
            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;

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";

            // 将表单内容写入请求体
            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();
        }
    }
}

标签:HTTP,String,org,new,apache,import,response,请求
From: https://www.cnblogs.com/eiffelzero/p/17713721.html

相关文章

  • python request请求数据
    pythonrequest请求数据#-*-coding:utf-8-*-importrequestsimportjson#查询塔吊X数据defsearchTowerXValue():towerXValue=0.0try:#从服务器请求数据response=requests.get('https://www.baidu.com:8087/sX')#检查响应......
  • Harbor部署(HTTP版)
    下载安装包在harbor版本下载需要的在线或离线安装包下载安装包以离线安装包为例wgethttps://github.com/goharbor/harbor/releases/download/v2.8.2/harbor-offline-installer-v2.8.2.tgz解压tar-zxvfharbor-offline-installer-v2.8.2.tgzharbor/harbor.v2.8......
  • 指定请求头部爬取知乎网
    1、获取知乎网的url2、检查后台--获取header信息3、获取json数据4、输出数据......
  • HttpClient采集页面数据
    1、导入相关依赖<!--https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-client--><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-client</artifactId><version>3.3.0</version&......
  • Django如何http接收+返回docx文件,文件名中文
     fromdjango.utils.encodingimportescape_uri_pathfromdjango.httpimportHttpResponse view中函数:filepath="文件路径"withopen(filepath,'rb')asf:content=f.read()response=HttpResponse(conte......
  • netty发送socket短连接请求,自定义报文头
    packagecom.chinaums.japi.util;importio.netty.bootstrap.Bootstrap;importio.netty.buffer.ByteBuf;importio.netty.buffer.Unpooled;importio.netty.channel.*;importio.netty.channel.nio.NioEventLoopGroup;importio.netty.channel.socket.SocketChannel;......
  • HTTP静态、动态住宅ip代理和数据中心代理是什么?有什么区别?
    随着时代的进步和互联网的发展,互联网中大部分企业的业务中可能需要用到代理ip。其中不仅有静态住宅ip代理和动态住宅ip代理还有数据中心代理,这些代理是什么?住宅ip代理和数据中心代理有什么异同点?小编接下来就跟大家介绍一下什么是住宅代理;什么是静态代理ip;什么是动态代理ip;什么是数......
  • 关于getClass().getClassLoader().getResourceAsStream——转载自https://www.cnblogs
    关于getClass().getClassLoader().getResourceAsStreamInputStreamis=getClass().getClassLoader().getResourceAsStream("helloworld.properties");getClass():取得当前对象所属的Class对象getClassLoader():取得该Class对象的类装载器类装载器负责从Java字符文件将字符流读......
  • 高匿HTTP能被地图识别嘛
    不知道大家有没有试过高匿HTTP在使用地图时到底能不能识别呢?今天,我就来探讨一下这个话题。首先,让我们来看看高匿HTTP是什么。高匿HTTP是一种可以隐藏你真实IP地址的HTTP服务,它会为你的网络请求提供一个虚拟的IP地址,让你在互联网上变得更加安全。但是,有人会问,既然高匿HTTP可以隐藏真......
  • Microsoft Edge浏览器如何设置HTTP代理
    当使用MicrosoftEdge浏览器时,你可以通过以下步骤设置代理IP,让浏览器使用代理服务器进行网络请求。步骤一:打开MicrosoftEdge浏览器设置在浏览器中点击右上角的菜单按钮(通常是三个水平点或者更多选项),然后选择"Settings"或者"设置"选项。步骤二:进入网络设置在浏览器设置界面中,向下滚......