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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM