HttpClient的请求方式有很多,其实本质都一样,下面我来介绍一下,Apache中的HttpClient
一、首先我们需要将Apache HttpClient的依赖包引用进来
<dependency>
<span style="white-space:pre"> </span><groupId>commons-httpclient</groupId>
<span style="white-space:pre"> </span><artifactId>commons-httpclient</artifactId>
<span style="white-space:pre"> </span><version>3.1</version>
</dependency>
二、请求有两种,分别是Http和Https
1、Http
public static String sendJsonWithHttp(String surl, String json) throws Exception
{
URL url = new URL(surl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestMethod("POST");// 提交模式
conn.setRequestProperty("Content-Length", json.getBytes().length + "");
conn.setConnectTimeout(100000);// 连接超时单位毫秒 //
conn.setReadTimeout(200000);// 读取超时 单位毫秒
conn.setDoOutput(true);// 是否输入参数
conn.setDoInput(true);
conn.setUseCaches(false);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(json.getBytes());
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
reader.close();
conn.disconnect();
return sb.toString();
}
2、Https
final static String PROTOCOL_NAME = "https";
public static String sendJsonWithHttps(String surl, String json) throws Exception
{
HttpClient client = new HttpClient();
client.getParams().setContentCharset("UTF-8");
Protocol httpProtocol = new Protocol(PROTOCOL_NAME, new SSLProtocolSocketFactory(false), 443);
Protocol.registerProtocol(PROTOCOL_NAME, httpProtocol);
PostMethod post = new PostMethod(surl);
post.setRequestHeader("Content-Type", "application/json");
RequestEntity requestEntity = new ByteArrayRequestEntity(json.getBytes("utf-8"));
post.setRequestEntity(requestEntity);
client.executeMethod(post);
InputStream in = post.getResponseBodyAsStream();
byte[] buf = new byte[512];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
do
{
int n = in.read(buf);
if (n > 0)
{
baos.write(buf, 0, n);
}
else if (n <= 0)
{
break;
}
} while (true);
return baos.toString();
}
仅供参考!