程序如下:
添加apache相关maven依赖:
1 <dependency> 2 <groupId>org.apache.commons</groupId> 3 <artifactId>commons-lang3</artifactId> 4 <version>3.7</version> 5 </dependency>
POST请求如下:
1 import com.alibaba.fastjson.JSONObject; 2 import org.apache.http.HttpEntity; 3 import org.apache.http.NameValuePair; 4 import org.apache.http.client.entity.UrlEncodedFormEntity; 5 import org.apache.http.client.methods.CloseableHttpResponse; 6 import org.apache.http.client.methods.HttpGet; 7 import org.apache.http.client.methods.HttpPost; 8 import org.apache.http.client.utils.URIBuilder; 9 import org.apache.http.entity.StringEntity; 10 import org.apache.http.impl.client.CloseableHttpClient; 11 import org.apache.http.impl.client.HttpClients; 12 import org.apache.http.message.BasicHeader; 13 import org.apache.http.message.BasicNameValuePair; 14 import org.apache.http.util.EntityUtils; 15 import org.slf4j.Logger; 16 import org.slf4j.LoggerFactory; 17 import java.util.ArrayList; 18 import java.util.List; 19 20 /** 21 * HttpClient发送POST请求 22 */ 23 public class HttpClientService { 24 25 26 /** 27 * 发送POST请求 28 * @param url 29 * @param map集合 30 * @return JSON 31 * @throws Exception 32 */ 33 public static Object sendPost(String url, Map<String, String> map) throws Exception{ 34 JSONObject jsonObject = null; 35 CloseableHttpClient client = null; 36 CloseableHttpResponse response = null; 37 try{ 38 /** 39 * 创建一个httpclient对象 40 */ 41 client = HttpClients.createDefault(); 42 /** 43 * 创建一个post对象 44 */ 45 HttpPost post = new HttpPost(url); 46 47 JSONObject jsonParam = new JSONObject(); 48 Set<String> set = map.keySet(); 49 for (String str : set) {//将Map转换成JSONObject 50 jsonParam.put(str, map.get(str)); 51 } 52 JSONArray jsonArray = new JSONArray(); 53 jsonArray.add(jsonParam);//将JSONObject转换成JSONArray入参 54 55 /** 56 * 设置上传byte[]数组文件流 57 builder.addBinaryBody("data", byteOutStream.toByteArray(), ContentType.MULTIPART_FORM_DATA, "AudioFile.wav"); 58 HttpEntity entity = builder.build(); 59 */ 60 61 /** 62 * 设置上传单一对象 63 */ 64 StringEntity entity = new StringEntity(jsonArray.toString(), "utf-8"); 65 66 /** 67 * 设置请求的内容 68 */ 69 post.setEntity(entity); 70 /** 71 * 设置请求的报文头部的编码 72 */ 73 post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); 74 /** 75 * 设置请求的报文头部的编码 76 */ 77 post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8")); 78 /** 79 * 执行post请求 80 */ 81 response = client.execute(post); 82 /** 83 * 获取响应码 84 */ 85 int statusCode = response.getStatusLine().getStatusCode(); 86 if (200 == statusCode){ 87 /** 88 * 通过EntityUitls获取返回内容 89 */ 90 String result = EntityUtils.toString(response.getEntity(),"UTF-8"); 91 /** 92 * 转换成json,根据合法性返回json或者字符串 93 */ 94 try{ 95 jsonObject = JSONObject.parseObject(result); 96 return jsonObject; 97 }catch (Exception e){ 98 return result; 99 } 100 }else{ 101 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!"); 102 } 103 }catch (Exception e){ 104 LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e); 105 }finally { 106 response.close(); 107 client.close(); 108 } 109 return null; 110 } 111 112 }
GET请求如下:
1 import com.alibaba.fastjson.JSONObject; 2 import org.apache.http.HttpEntity; 3 import org.apache.http.NameValuePair; 4 import org.apache.http.client.entity.UrlEncodedFormEntity; 5 import org.apache.http.client.methods.CloseableHttpResponse; 6 import org.apache.http.client.methods.HttpGet; 7 import org.apache.http.client.methods.HttpPost; 8 import org.apache.http.client.utils.URIBuilder; 9 import org.apache.http.entity.StringEntity; 10 import org.apache.http.impl.client.CloseableHttpClient; 11 import org.apache.http.impl.client.HttpClients; 12 import org.apache.http.message.BasicHeader; 13 import org.apache.http.message.BasicNameValuePair; 14 import org.apache.http.util.EntityUtils; 15 import org.slf4j.Logger; 16 import org.slf4j.LoggerFactory; 17 import java.util.ArrayList; 18 import java.util.List; 19 20 /** 21 * HttpClient发送GET请求 22 */ 23 public class HttpClientService { 24 25 26 /** 27 * 发送GET请求 28 * @param url请求url 29 * @param name请求参数 30 * @return JSON 31 * @throws Exception 32 */ 33 public static Object sendGet(String url,String name) throws Exception{ 34 JSONObject jsonObject = null; 35 CloseableHttpClient client = null; 36 CloseableHttpResponse response = null; 37 try{ 38 /** 39 * 创建HttpClient对象 40 */ 41 client = HttpClients.createDefault(); 42 /** 43 * 创建URIBuilder 44 */ 45 URIBuilder uriBuilder = new URIBuilder(url); 46 47 /** 48 * 设置参数 49 */ 50 uriBuilder.addParameters(name); 51 /** 52 * 创建HttpGet 53 */ 54 HttpGet httpGet = new HttpGet(uriBuilder.build()); 55 /** 56 * 设置请求头部编码 57 */ 58 httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); 59 /** 60 * 请求服务 61 */ 62 response = client.execute(httpGet); 63 /** 64 * 获取响应吗 65 */ 66 int statusCode = response.getStatusLine().getStatusCode(); 67 68 if (200 == statusCode){ 69 /** 70 * 获取返回对象 71 */ 72 HttpEntity entity = response.getEntity(); 73 /** 74 * 通过EntityUitls获取返回内容 75 */ 76 String result = EntityUtils.toString(entity,"UTF-8"); 77 /** 78 * 转换成json,根据合法性返回json或者字符串 79 */ 80 try{ 81 jsonObject = JSONObject.parseObject(result); 82 return jsonObject; 83 }catch (Exception e){ 84 return result; 85 } 86 }else{ 87 LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败!"); 88 } 89 }catch (Exception e){ 90 LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e); 91 } finally { 92 response.close(); 93 client.close(); 94 } 95 return null; 96 } 97 98 }
文章参考:
总语:
我是南国以南i记录点滴每天成长一点点,学习是永无止境的!转载请附原文链接!!!