【httpclient编写爬虫】post提交json数据和普通键值

来源:互联网 发布:淘宝中上传宝贝到仓库 编辑:程序博客网 时间:2024/06/01 08:01

写在开头

在开发爬虫的过程中,难免碰到post提交的问题。
本文比较了两种数据提交方式,并且使用httpclient模拟网站post提交两种数据。

我见过的post提交方式有两种:

  1. 普通的键值对提交方式;
  2. 提交json数据。

我所使用的httpclient版本

<dependency>    <groupId>org.apache.httpcomponents</groupId>    <artifactId>httpclient</artifactId>    <version>4.5.2</version></dependency>

普通键值对的提交方式

CloseableHttpClient httpclient = HttpClients.createDefault();HttpPost httpPost = new HttpPost("http://targethost/login");List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("username", "vip"));nvps.add(new BasicNameValuePair("password", "secret"));httpPost.setEntity(new UrlEncodedFormEntity(nvps));CloseableHttpResponse response2 = httpclient.execute(httpPost);try {    System.out.println(response2.getStatusLine());    HttpEntity entity2 = response2.getEntity();    // do something useful with the response body    // and ensure it is fully consumed    EntityUtils.consume(entity2);} finally {    response2.close();}

JSON数据提交方式

要提交的数据

{    "username" : "vip",    "password" : "secret"}

代码

import org.apache.http.Consts;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.util.EntityUtils;import java.io.IOException;/** * Created by CarlZhang on 2017/1/1. */public class PostJsonTest {    public static void main(String[] args) {        CloseableHttpClient httpclient = HttpClients.createDefault();        try {            HttpPost httpPost = new HttpPost("http://targethost/login");            //json数据{"username":"vip","password":"secret"}            String jsonStr  = "{\"username\":\"vip\",\"password\":\"secret\"}";            StringEntity se = new StringEntity(jsonStr, Consts.UTF_8);            se.setContentEncoding("UTF-8");            se.setContentType("application/json");            httpPost.setEntity(se);            CloseableHttpResponse response2 = httpclient.execute(httpPost);            try {                System.out.println(response2.getStatusLine());                HttpEntity entity2 = response2.getEntity();                // do something useful with the response body                // and ensure it is fully consumed                //EntityUtils.consume(entity2);                String res = EntityUtils.toString(entity2);                System.out.println(res);            } finally {                response2.close();            }        } catch (IOException e) {            e.printStackTrace();        }finally {            try {                httpclient.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

实例-JSON提交

如下是我在某个网站点击发帖,然后在chrome (按住F12键)打开的dubug工具,可以看到我提交的post请求。其中Form Data就是使用post提交的json数据。
这里写图片描述

后端怎么拿到这些数据的呢?
该网站使用的开源库latke中的Requests类
可以看到,它是通过Reader对象去读入流数据的。

 /**     * Gets the request json object with the specified request.     *     * @param request the specified request     * @param response the specified response, sets its content type with "application/json"     * @return a json object     * @throws ServletException servlet exception     * @throws IOException io exception     */    public static JSONObject parseRequestJSONObject(final HttpServletRequest request, final HttpServletResponse response)        throws ServletException, IOException {        response.setContentType("application/json");        final StringBuilder sb = new StringBuilder();        BufferedReader reader;        final String errMsg = "Can not parse request[requestURI=" + request.getRequestURI() + ", method=" + request.getMethod()            + "], returns an empty json object";        try {            try {                reader = request.getReader();            } catch (final IllegalStateException illegalStateException) {                reader = new BufferedReader(new InputStreamReader(request.getInputStream()));            }            String line = reader.readLine();            while (null != line) {                sb.append(line);                line = reader.readLine();            }            reader.close();            String tmp = sb.toString();            if (Strings.isEmptyOrNull(tmp)) {                tmp = "{}";            }            return new JSONObject(tmp);        } catch (final Exception ex) {            LOGGER.log(Level.ERROR, errMsg, ex);            return new JSONObject();        }    }

另外,前端js代码是通过jquery的类库去提交的json数据
这里写图片描述

实例-普通post提交

这里写图片描述

有兴趣可以查看我这篇文章【js类库AngularJs】解决angular+springmvc的post提交问题

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 支付宝换手机了怎么办 退款了但货到了怎么办 淘宝店铺封了钱怎么办 淘宝被扣24分后怎么办 恶意拍下并付款怎么办 包裹被退回去了怎么办 以前开过淘宝店怎么办 原来开过淘宝店怎么办 微信申诉失败该怎么办 淘宝号登录不上怎么办 淘宝账户忘了怎么办啊 支付宝没钱了怎么办啊 京东不支持自提怎么办 苹果7淘宝不能用怎么办 退货卖家不理人怎么办 淘宝购物车满了怎么办 微商不想做了货怎么办 淘宝网店没人买怎么办 运费险没有到账怎么办 小蓝押金退不了怎么办 招行登录是乱码怎么办 淘宝代付被骗了怎么办 欠增值税票不开怎么办 征信不好急用钱怎么办 翼讯账号忘了怎么办 易迅改版后售后怎么办 第二件半价要退怎么办 办手机分期不还怎么办 杜鹃鸟被识破了怎么办 医保被别人用了怎么办 天猫洗衣机坏了怎么办 苏宁任性付逾期怎么办 买了衣服后悔了怎么办 苏宁退货无发票怎么办 丽达购物卡过期怎么办 忘了京东账号怎么办 京东账户忘记了怎么办 三星c7开不了机怎么办 三星手机为什么开不了机怎么办 美图m4屏幕失灵怎么办 美图手机摔黑屏怎么办