文章目录

一、第1种方式
1. 因依赖
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
2. 工具类+测试方法
package com.gblfy;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.InputStream;
import java.io.InputStreamReader;


public class HTTPUtils {

/**
* 协议类型:HTTP
* 请求方式:POST
* 报文格式:json
* 编码设置:UTF-8
* 响应类型:jsonStr
*
* @param url
* @param json
* @return
* @throws Exception
*/
public static String postJosnContent(String url, String json) throws Exception {
System.out.println("请求接口参数:" + json);
PostMethod method = new PostMethod(url);
HttpClient httpClient = new HttpClient();
try {
RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
method.setRequestEntity(entity);
httpClient.executeMethod(method);
System.out.println("请求接口路径url:" + method.getURI().toString());
InputStream in = method.getResponseBodyAsStream();
//下面将stream转换为String
StringBuffer sb = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
char[] b = new char[4096];
for (int n; (n = isr.read(b)) != -1; ) {
sb.append(new String(b, 0, n));
}
String returnStr = sb.toString();
return returnStr;
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
method.releaseConnection();
}
}

public static void main(String[] args) throws Exception {
String url = "http://localhost:8080/httptojson";
String json = "{\"name\":\"gblfy\"}";
String res = postJosnContent(url, json);
System.out.println("响应报文:" + res);
}
}
3. 服务端接收
package com.gblfy;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class AController {

@RequestMapping(value = "/postToJson", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String postToJson(@RequestBody String json) {
System.out.println(json);
return json;
}
}
二、第2种方式

和第一种方式基本一样

public static byte[] post(String url, String content, String charset) throws IOException {

URL console = new URL(url);
HttpURLConnection conn = (HttpURLConnection) console.openConnection();
conn.setDoOutput(true);
// 设置请求头
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// 刷新、关闭
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toByteArray();
}
return null;
}
三、第3种方式
3.1. 引依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
3.2. 工具类+测试
package com.gblfy.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;

/**
* @author Mundo
* @ClassName: HttpClientUtil
* @Description: TODO
*/

public class HttpApiUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpApiUtil.class);

/**
*
* @param url 请求路径
* @param params 参数
* @return
*/
public static String doGet(String url, Map<String, String> params) {

// 返回结果
String result = "";
// 创建HttpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = null;
try {
// 拼接参数,可以用URIBuilder,也可以直接拼接在?传值,拼在url后面,如下--httpGet = new
// HttpGet(uri+"?id=123");
URIBuilder uriBuilder = new URIBuilder(url);
if (null != params && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
// 或者用
// 顺便说一下不同(setParameter会覆盖同名参数的值,addParameter则不会)
// uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
URI uri = uriBuilder.build();
// 创建get请求
httpGet = new HttpGet(uri);
logger.info("访问路径:" + uri);
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 返回200,请求成功
// 结果返回
result = EntityUtils.toString(response.getEntity());
logger.info("请求成功!,返回数据:" + result);
} else {
logger.info("请求失败!");
}
} catch (Exception e) {
logger.info("请求失败!");
logger.error(ExceptionUtils.getStackTrace(e));
} finally {
// 释放连接
if (null != httpGet) {
httpGet.releaseConnection();
}
}
return result;
}

/**
* @param url
* @param params
* @return
* @Title: doPost
* @Description: post请求
* @author Mundo
*/
public static String doPost(String url, Map<String, String> params) {
String result = "";
// 创建httpclient对象
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
try { // 参数键值对
if (null != params && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair = null;
for (String key : params.keySet()) {
pair = new BasicNameValuePair(key, params.get(key));
pairs.add(pair);
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("返回数据:>>>" + result);
} else {
logger.info("请求失败!,url:" + url);
}
} catch (Exception e) {
logger.error("请求失败");
logger.error(ExceptionUtils.getStackTrace(e));
e.printStackTrace();
} finally {
if (null != httpPost) {
// 释放连接
httpPost.releaseConnection();
}
}
return result;
}

/**
* post发送json字符串
* @param url
* @param params
* @return 返回数据
* @Title: sendJsonStr
*/
public static String sendJsonStr(String url, String params) {
String result = "";

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
if (StringUtils.isNotBlank(params)) {
httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
}
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
logger.info("返回数据:" + result);
} else {
logger.info("请求失败");
}
} catch (IOException e) {
logger.error("请求异常");
logger.error(ExceptionUtils.getStackTrace(e));
}
return result;
}

/**
* 发送http请求的obj报文(内置转json)
*
* @param url
* @param obj
* @return
*/
public static String postJson(String url, Object obj) {
HttpURLConnection conn = null;
try {
// 创建一个URL对象
URL mURL = new URL(url);
// 调用URL的openConnection()方法,获取HttpURLConnection对象
conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod("POST");// 设置请求方法为post
/* conn.setReadTimeout(5000);// 设置读取超时为5秒
conn.setConnectTimeout(10000);// 设置连接网络超时为10秒*/
conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容
// 设置文件类型:
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 设置接收类型否则返回415错误
conn.setRequestProperty("accept", "application/json");
int len = 0;
// post请求的参数
byte[] buf = new byte[10240];
//
String data = JSONObject.toJSONString(obj);

// 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
out.write(data.getBytes());
out.flush();
out.close();

int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
if (responseCode == 200) {
InputStream is = conn.getInputStream();
String state = getStringFromInputStream(is);
return state;
} else {
System.out.print("访问失败" + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();// 关闭连接
}
}
return null;
}

public static String getStringFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 模板代码 必须熟练
byte[] buffer = new byte[1024];
int len = -1;
// 一定要写len=is.read(buffer)
// 如果while((is.read(buffer))!=-1)则无法将数据写入buffer中
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
is.close();
String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
os.close();
return state;
}

/**
* post方式请求服务器(http协议)
*
* @param url 请求地址
* @param content 参数
* @param charset 编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static byte[] post(String url, String content, String charset) throws IOException {

URL console = new URL(url);
HttpURLConnection conn = (HttpURLConnection) console.openConnection();
conn.setDoOutput(true);
// 设置请求头
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// 刷新、关闭
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toByteArray();
}
return null;
}

public static void main(String[] args) {
//测试1 get发送map
Map<String, String> map = new HashMap<String, String>();
map.put("id", UUID.randomUUID().toString());
map.put("name", "gblfy");
String get = doGet("http://localhost:8080/getToMap", map);
System.out.println("get请求调用成功,返回数据是:" + get);

//测试2 post发送map
// String post = doPost("http://localhost:8080/httptojson", map);
// System.out.println("post调用成功,返回数据是:" + post);

//测试3 post发送json字符串
// String json = sendJsonStr("http://localhost:8080/httptojson", "{\"name\":\"ly\"}");
// System.out.println("json发送成功,返回数据是:" + json);

//测试4 post发送obj对象
// User user = new User();
// user.setUsername("POST_JSON");
// user.setAge(12);
// user.setPasswd("00990099");
// String json = postJson("http://localhost:8080/httptojson", user);
// System.out.println("json发送成功,返回数据是:" + json);

}
}
3.3. 服务端代码
package com.gblfy;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class AController {

@RequestMapping(value = "/postToJson", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String postToJson(@RequestBody String json) {
System.out.println(json);
return json;
}

@RequestMapping(value = "/getToMap", method = RequestMethod.GET)
public String getToMap(@RequestParam(name = "id") String id,
@RequestParam(name = "name") String name) {
System.out.println(id);
System.out.println(name);
StringBuffer buf = new StringBuffer();
buf.append(id);
buf.append(name);
return buf.toString();
}
}