java模拟浏览器请求

本文介绍如何使用Java的HttpClient库和JDK自带的HttpURLConnection实现HTTP客户端。通过示例代码展示了POST请求的发送过程,包括设置请求头、构建请求参数、处理响应等关键步骤。
  1. 利用httpclient4.× 写一个http的客户端
    1. public void post(List<NameValuePair> payload) throws  Exception{     
    2.         HttpPost post = new HttpPost(uri);     
    3.         HttpEntity result = null;     
    4.         try {     
    5.             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(payload,     
    6.                     charset);     
    7.             post.setEntity(entity);     
    8.             if (LOG.isDebugEnabled()) {     
    9.                 LOG.debug("sending:" + payload);     
    10.             }     
    11.      
    12.             HttpResponse response = _httpClient.execute(post);     
    13.             StatusLine statusLine = response.getStatusLine();     
    14.             if (statusLine.getStatusCode() != HttpStatus.SC_OK) {     
    15.                 result = response.getEntity();     
    16.                 StringBuilder msg = new StringBuilder();     
    17.                 msg.append("http response with code "     
    18.                         + statusLine.getStatusCode());     
    19.                 msg.append("\n");     
    20.                 msg.append("post request: " + post.getURI());     
    21.                 msg.append("\n");     
    22.                 msg.append(statusLine.getReasonPhrase());     
    23.                 if (result != null) {     
    24.                     msg.append("\n\n");     
    25.                     msg.append(EntityUtils.toString(result, "UTF-8"));     
    26.                     msg.append("\n\n");     
    27.                 }     
    28.                 throw new UmcException(msg.toString());     
    29.             }     
    30.             if (response.getEntity() != null) {     
    31.                 BufferedReader reader = new BufferedReader(     
    32.                         new InputStreamReader(     
    33.                                 response.getEntity().getContent(), "UTF-8"));     
    34.                 String line = null;     
    35.                 while ((line = reader.readLine()) != null) {     
    36.                     if (line.indexOf("success") < 0)     
    37.                         System.out.println(line);     
    38.                 }     
    39.             }     
    40.         } finally {     
    41.             if (result != null)     
    42.                 try {     
    43.                     EntityUtils.consume(result);     
    44.                 } catch (IOException e) {     
    45.                 }     
    46.             post.abort();     
    47.         }     
    48.     }    
  2. 采用JDK的HttpConnection构造http客户端
    1. ////发送     
    2.     HttpURLConnection conn = null;     
    3.     try {     
    4.         URL url = new URL(Your_URL);     
    5.         conn = (HttpURLConnection) url.openConnection();     
    6.         conn.setRequestMethod("POST");     
    7.         conn.setRequestProperty("Content-Type",     
    8.                 "application/x-www-form-urlencoded");     
    9.         conn.setUseCaches(false);     
    10.         conn.setDoOutput(true);     
    11.         OutputStreamWriter osw = new OutputStreamWriter(     
    12.                 conn.getOutputStream());     
    13.         StringBuffer sb = new StringBuffer();     
    14.         addPair(sb, "p1""p1value");     
    15.         addPair(sb, "p2""p2value");     
    16.         osw.write(sb.substring(0, sb.length() - 1));     
    17.         osw.flush();     
    18.         BufferedReader reader = new BufferedReader(     
    19.                 new InputStreamReader(conn.getInputStream()));     
    20.         String line = null;     
    21.         sb = new StringBuffer();     
    22.         while ((line = reader.readLine()) != null) {     
    23.             sb.append(line);     
    24.         }     
    25.         line = sb.toString();     
    26.         // 处理返回的字符串line     
    27.         return;     
    28.         ////     
    29.     } catch (IOException e) {     
    30.         // handle e     
    31.     } finally {     
    32.         if (conn != null)     
    33.             conn.disconnect();     
    34.     }///发送结束
    1. public static void addPair(StringBuffer sb, String name, String value) {     
    2.     if (value == null) {     
    3.         return;     
    4.     }     
    5.     sb.append(name);     
    6.     sb.append("=");     
    7.     sb.append(value);     
    8.     sb.append("&");     
    9. }    


### Java 实现 POST 请求 为了使用 Java 模拟浏览器发送 POST 请求,`HttpURLConnection` 是一种常用的方式。下面是一个完整的例子来展示如何构建并发送带有参数的 HTTP POST 请求[^1]。 ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class PostExample { private final String USER_AGENT = "Mozilla/5.0"; public static void main(String[] args) throws Exception { new PostExample().sendPost(); } // 发送POST请求到给定URL public void sendPost() throws Exception { String url = "http://example.com/api"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置基本属性 con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // 设置为true表示允许输入和输出流操作 con.setDoOutput(true); // 构建表单数据字符串 String urlParameters = "param1=value1&param2=value2"; // 发送POST请求中的参数 try(OutputStream os = con.getOutputStream()) { byte[] input = urlParameters.getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = con.getResponseCode(); System.out.println("POST Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应 // 处理成功后的逻辑... } else { // 错误处理... } } } ``` 此代码片段展示了创建 `HttpURLConnection` 对象的过程,并设置了必要的头部信息以及通过输出流写入要传递的数据。注意这里指定了 User-Agent 字符串模仿真实浏览器行为[^4]。此外,在设置连接对象时启用了输出模式 (`setDoOutput`) 来准备发送数据。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值