java 利用common-httpclient包来实现post请求

1 篇文章 0 订阅

项目中需要请求第三方接口,而且要求请求参数数据为json类型的。本来首先使用的是httpclient的jar包,但是因为项目中已经使用了common-httpclient的jar包,引起了冲突,所以不得不使用common-httpclient来实现。

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HTTPUtils {

    private static Logger logger = LoggerFactory.getLogger(HTTPUtils.class);

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String postJosnContent(String url, String Json) throws Exception {
//      HttpPost method = new HttpPost(url);  
//      DefaultHttpClient httpClient = new DefaultHttpClient();  
//      String ret = null;
//      try {
//           StringEntity entity = new StringEntity(Json,"UTF-8");//解决中文乱码问题     
//             entity.setContentEncoding("UTF-8");    
//             entity.setContentType("application/json");
//             method.setEntity(entity);    
//             HttpResponse result = httpClient.execute(method);  
//             ret = EntityUtils.toString(result.getEntity());  
//      } catch (Exception e) {
//          throw e;
//      } finally {
//          method.releaseConnection();
//      }
//      return ret;
        logger.error("请求接口参数:" + Json);
        PostMethod method = new PostMethod(url);
        HttpClient httpClient = new HttpClient();
        try {
            RequestEntity entity = new StringRequestEntity(Json,"application/json","UTF-8");
            method.setRequestEntity(entity);
            httpClient.executeMethod(method);
            logger.error("请求接口路径url:" + method.getURI().toString());
            InputStream in = method.getResponseBodyAsStream();
            //下面将stream转换为String
            StringBuffer sb = new StringBuffer();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            char[] b = new char[4096];
            for(int n; (n = isr.read(b)) != -1;) {
                sb.append(new String(b, 0, n));
            }
            String returnStr = sb.toString();
            return returnStr;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            method.releaseConnection();
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Java中的HTTPClient请求multipart/form-data,你可以使用Apache HttpClient库来实现。下面是一个简单的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.HttpClients; import java.io.File; import java.io.IOException; public class MultipartFormDataExample { public static void main(String[] args) { HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/upload"); // 创建一个多部分实体构建器 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文本参数 builder.addTextBody("username", "John Doe"); // 添加文件参数 File file = new File("path/to/image.jpg"); builder.addBinaryBody("image", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); // 构建多部分实体 HttpEntity multipartEntity = builder.build(); // 将多部分实体设置为请求的实体 httpPost.setEntity(multipartEntity); try { // 执行请求 HttpResponse response = httpClient.execute(httpPost); // 处理响应 // ... } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,我们使用了Apache HttpClient库来进行HTTP请求。首先,我们创建一个`HttpClient`实例,并指定要进行POST请求的URL。然后,我们创建一个`MultipartEntityBuilder`实例,用于构建多部分实体。我们可以使用`addTextBody`方法添加文本参数,使用`addBinaryBody`方法添加文件参数。最后,我们通过调用`build`方法构建多部分实体,并将其设置为POST请求的实体。最后,我们执行请求并处理响应。 希望以上的示例代码能对你有所帮助。<span class="em">1</span> #### 引用[.reference_title] - *1* [c#实现HttpClient拼接multipart/form-data形式参数post提交数据](https://download.csdn.net/download/kgo00/12091747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值