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

1.用到HttpClient

对应的maven依赖:

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

      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.25</version>

      </dependency>

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<NameValuePair> params = new ArrayList<NameValuePair>();
        //设置请求地址是://
        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);
        }


    }





}

 

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java模拟POST方式提交表单实现图片上传,可以通过使用JavaHttpURLConnection类来实现。以下是一个示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; public class ImageUploader { public static void uploadImage(File imageFile, String uploadUrl) throws IOException { String boundary = UUID.randomUUID().toString(); String lineEnd = "\r\n"; String twoHyphens = "--"; URL url = new URL(uploadUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); OutputStream outputStream = conn.getOutputStream(); // 添加图片文件 FileInputStream inputStream = new FileInputStream(imageFile); outputStream.write((twoHyphens + boundary + lineEnd).getBytes()); outputStream.write(("Content-Disposition:form-data;name=\"file\";filename=\"" + imageFile.getName() + "\"" + lineEnd).getBytes()); outputStream.write(("Content-Type:application/octet-stream" + lineEnd).getBytes()); outputStream.write((lineEnd).getBytes()); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } inputStream.close(); outputStream.write((lineEnd).getBytes()); // 添加表单参数 outputStream.write((twoHyphens + boundary + lineEnd).getBytes()); outputStream.write(("Content-Disposition:form-data;name=\"param1\"" + lineEnd).getBytes()); outputStream.write((lineEnd).getBytes()); outputStream.write(("value1" + lineEnd).getBytes()); outputStream.write((twoHyphens + boundary + twoHyphens + lineEnd).getBytes()); outputStream.flush(); outputStream.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 上传成功 } else { // 上传失败 } } } ``` 在以上示例代码中,通过HttpURLConnection类来连接上传服务器,设置请求方式为POST,然后通过OutputStream将图片文件和表单参数发送给服务器。在发送之前需要设置Content-Type为multipart/form-data,并且在每个参数之间通过boundary分隔。最后通过getResponseCode()方法获取服务器的响应码,判断上传是否成功。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值