10-18-2024, 12:22
今天对接第三方接口,遇到个奇怪的方式,要求使用HttpGet发送FormData,但是吧使用HttpGet发送FormData格式的数据不是标准做法,因为HttpGet通常用于获取资源,它的设计不包括请求体(request body)。当然人家既然弄出这样的接口,就表示一般是可以实现的,
以下是实现源码以上就是本次实现 使用HttpGet发送formdata格式数据的解决办法
以下是实现源码
- HttpGetWithBody继承HttpEntityEnclosingRequestBase ,而HttpEntityEnclosingRequestBase支持携带body
代码:
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
/**
* httpget带body
*
* @author 1dream.fun
* @since 2024/10/15 14:54
*/
public class HttpGetWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "GET";
HttpGetWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
- 接口实现,具体以实际需求进行改动
代码:
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* 获取form请求结果
* @param url 地址
* @param headers 请求头
* @param body 请求form参数
* @date 2024/10/18 11:08
* @return java.lang.String
*/
private static String getWithForm(String url, Map<String,String> headers,Map<String,Object> body) throws IOException {
HttpGetWithBody httpGet = new HttpGetWithBody(url);
headers.forEach(httpGet::setHeader);
final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
body.forEach((k,v)-> multipartEntityBuilder.addTextBody(k, Optional.ofNullable(v).map(Object::toString).orElse("")));
httpGet.setEntity(multipartEntityBuilder.build());
return EntityUtils.toString(HttpClients.createDefault().execute(httpGet).getEntity());
}
