java模拟http发送post请求提交表单

1.用到HttpClient

对应的maven依赖:

    
      org.apache.httpcomponents
      httpclient
        4.5.2
    

      
          org.slf4j
          slf4j-log4j12
          1.7.25

      

resources下的配置文件:log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.logger.cn.itcast=DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

对应的java代码:

package com.cyou.tian;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;


public class PostTest {


    public static void main(String[] args) throws Exception {

        //创建HttpClient对象
        //1.打开浏览器,创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.输入网址,发起请求创建HttpPost对象,设置url访问地址
        HttpPost httpPost = new HttpPost("http://10.12.28.162:8080/putgoods");



        //声明List集合,封装表单中的参数
        List params = new ArrayList();
        //设置请求地址是://
        params.add(new BasicNameValuePair("version","1.0"));


        //创建表单的Entity对象,第一个参数就是封装好的表单数据,第二个参数就是编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf8");

        //设置表单的Entity对象到Post请求中

        httpPost.setEntity(formEntity);


        CloseableHttpResponse response = httpClient.execute(httpPost);
        //4.解析响应,获取数据


        //判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200){
            HttpEntity httpEntity = response.getEntity();
            String content = EntityUtils.toString(httpEntity,"utf8");
            System.out.println(content);
        }


    }





}

 

你可能感兴趣的:(http)