java http delete_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 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> it = map.entrySet().iterator();

List params = new ArrayList();

while (it.hasNext()) {

Map.Entry 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则需要下面的类

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值