java发送http请求,get,post,delete

package com.odianyun.example.business.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
* 模拟http请求工具类
*
* @author matao
* @date 2016年7月14日
*/
public class HttpClientUtils {
private static CloseableHttpClient httpClient = createSSLClientDefault();

static int time=2000;
/**
* 发送GET请求
*
* @author matao
* @date 2016年7月19日
*/
public static String sendGet(String url) {
String responseContent = "";

HttpGet httpGet = new HttpGet(url);

try {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(time).setConnectionRequestTimeout(time).setSocketTimeout(time).build();
httpGet.setConfig(requestConfig);
HttpResponse response = httpClient.execute(httpGet);

if (response == null) {
return responseContent;
}

// 获得响应实体
HttpEntity resEntity = response.getEntity();
// 获得状态码
int statusCode = response.getStatusLine() == null ? 0 : response.getStatusLine().getStatusCode();
// 获得相应内容
if (resEntity != null && statusCode == 200) {
responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return responseContent;
}

/**
* 发送post数据类型为form-data
* @param url
* @param map
* @return
* @throws Exception
*/
public static String doPost(String url, HashMap<String, String> map) throws Exception {
String result = "";
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
.setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Charset", "UTF-8");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
List<NameValuePair> params = new ArrayList<NameValuePair>();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
params.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
try {
response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
} catch (ClientProtocolException e) {
throw new RuntimeException("创建连接失败" + e);
} catch (IOException e) {
throw new RuntimeException("创建连接失败" + e);
}

return result;

}

public static String doDelete(String data, String url) throws IOException {
CloseableHttpClient client = null;
com.odianyun.example.business.common.utils.HttpDeleteWithBody httpDelete = null;
String result = null;
try {
client = HttpClients.createDefault();
httpDelete = new com.odianyun.example.business.common.utils.HttpDeleteWithBody(url);

httpDelete.addHeader("Content-type","application/json; charset=utf-8");
httpDelete.setHeader("Accept", "application/json; charset=utf-8");
httpDelete.setEntity(new StringEntity(data));

CloseableHttpResponse response = client.execute(httpDelete);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);

if (200 == response.getStatusLine().getStatusCode()) {

}
} catch (Exception e) {
} finally {
client.close();
}
return result;

}




public static String sendPost(String url, Object params) {
// 响应内容
String responseContent = "";

HttpPost post = new HttpPost(url);

try {
// 设置请求实体
StringEntity reqEntity = new StringEntity(JSON.toJSONString(params), "utf-8");
reqEntity.setContentEncoding("UTF-8");
reqEntity.setContentType("application/json");
post.setEntity(reqEntity);



// 发送请求,返回响应对象
HttpResponse response = httpClient.execute(post);

if (response == null) {
return responseContent;
}

// 获得响应实体
HttpEntity resEntity = response.getEntity();
// 获得状态码
int statusCode = response.getStatusLine() == null ? 0 : response.getStatusLine().getStatusCode();
// 获取响应内容
if (resEntity != null && statusCode == HttpStatus.SC_OK) {
responseContent = EntityUtils.toString(resEntity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception ec){
ec.printStackTrace();
}

return responseContent;
}


public static String sendFormPost(String url, String params) {
// 响应内容
String responseContent = "";

HttpPost post = new HttpPost(url);

try {

// 设置请求实体
StringEntity reqEntity = new StringEntity(params, "utf-8");
reqEntity.setContentEncoding("UTF-8");
reqEntity.setContentType("application/x-www-form-urlencoded");
post.setEntity(reqEntity);



// 发送请求,返回响应对象
HttpResponse response = httpClient.execute(post);

if (response == null) {
return responseContent;
}

// 获得响应实体
HttpEntity resEntity = response.getEntity();
// 获得状态码
int statusCode = response.getStatusLine() == null ? 0 : response.getStatusLine().getStatusCode();
// 获取响应内容
if (resEntity != null && statusCode == HttpStatus.SC_OK) {
responseContent = EntityUtils.toString(resEntity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception ec){
ec.printStackTrace();
}

return responseContent;
}

/**
* 创建HttpClient对象(用于发送https请求)
*
* @author matao
* @date 2016年7月14日
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};

SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}

return HttpClients.createDefault();
}

public static void main(String[] args) {
String result = sendFormPost("https://www.XXX.com/forecom/login/ajax_b2b.shtml","username=1&password=1");

System.out.println(result);
}

}
上面的代码可以发送http的get以及post,如果需要发送delete则需要下面的类
package com.odianyun.example.business.common.utils;

/**
 * @ Author     :kxs.
 * @ Date       :Created in 14:30 2020/7/22
 * @ Description:${description}
 * @ Modified By:
 * @Version: $version$
 */
import java.net.URI;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase{
    public static final String METHOD_NAME = "DELETE";

    /**
     * 获取方法(必须重载)
     *
     * @return
     */
    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public HttpDeleteWithBody(final URI uri) {
        super();
        setURI(uri);
    }

    public HttpDeleteWithBody() {
        super();
    }

}

 发送post请求form-data格式的请求需要将对象转为Map<String, String>,参考链接:https://www.cnblogs.com/mm962464/p/13363313.html

posted @ 2020-07-22 16:19  以你为名的世界  阅读(2089)  评论(0编辑  收藏  举报