以前使用http连接都是网上百度个小demo然后拿来就用,对其并不是太了解,今天看了看这些东西,写下了,以防忘记
大体说一下,URLConnection其实就是Java类,其中的API比较少,可以扩展性比较大。HttpClient可以把它看成一个框架,很多API。用起来方便。另外使用起来也很多种,下面复制一些代码,包括post和Get的方法。
httpClient的Get的请求:
public
static
String HttpGet(String url)
throws
Exception{
String jsonString =
""
;
HttpClient client =
new
HttpClient(
new
HttpClientParams(),
new
SimpleHttpConnectionManager(
true
));
client.getHttpConnectionManager().getParams().setConnectionTimeout(
15000
);
//通过网络与服务器建立连接的超时时间
client.getHttpConnectionManager().getParams().setSoTimeout(
60000
);
//Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
GetMethod method =
new
GetMethod(url);
method.setRequestHeader(
"Content-Type"
,
"text/html;charset=UTF-8"
);
try
{
client.executeMethod(method);
jsonString = method.getResponseBodyAsString();
}
catch
(Exception e) {
jsonString =
"error"
;
logger.error(
"HTTP请求路径时错误:"
+ url, e.getMessage());
throw
e;
// 异常外抛
}
finally
{
if
(
null
!= method)
method.releaseConnection();
}
return
jsonString;
}
httpClient的POST的请求:
/**
* 普通POST请求
*/
@SuppressWarnings
(
"deprecation"
)
public
static
String HttpPost(String url, String body)
throws
Exception{
String jsonString =
""
;
HttpClient client =
new
HttpClient(
new
HttpClientParams(),
new
SimpleHttpConnectionManager(
true
));
client.getHttpConnectionManager().getParams().setConnectionTimeout(
15000
);
//通过网络与服务器建立连接的超时时间
client.getHttpConnectionManager().getParams().setSoTimeout(
60000
);
//Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
PostMethod method =
new
PostMethod(url);
method.setRequestHeader(
"Content-Type"
,
"text/html;charset=UTF-8"
);
method.setRequestBody(body);
try
{
client.executeMethod(method);
jsonString = method.getResponseBodyAsString();
}
catch
(Exception e) {
jsonString =
"error"
;
logger.error(
"HTTP请求路径时错误:"
+ url, e.getMessage());
throw
e;
// 异常外抛
}
finally
{
if
(
null
!= method)
method.releaseConnection();
}
return
jsonString;
}
/**
* JSON的POST请求
*/
@SuppressWarnings
(
"deprecation"
)
public
static
String HttpPostJSON(String url, JSONObject body)
throws
Exception{
String jsonString =
""
;
HttpClient client =
new
HttpClient(
new
HttpClientParams(),
new
SimpleHttpConnectionManager(
true
));
client.getHttpConnectionManager().getParams().setConnectionTimeout(
15000
);
//通过网络与服务器建立连接的超时时间
client.getHttpConnectionManager().getParams().setSoTimeout(
60000
);
//Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
client.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
"UTF-8"
);
PostMethod method =
new
PostMethod(url);
method.setRequestHeader(
"Content-Type"
,
"application/json;charset=UTF-8"
);
method.setRequestBody(body.toString());
try
{
client.executeMethod(method);
jsonString = method.getResponseBodyAsString();
}
catch
(Exception e) {
jsonString =
"error"
;
logger.error(
"HTTP请求路径时错误:"
+ url, e.getMessage());
throw
e;
// 异常外抛
}
finally
{
if
(
null
!= method)
method.releaseConnection();
}
return
jsonString;
}
/**
* XML的POST请求
*/
@SuppressWarnings
(
"deprecation"
)
public
static
String HttpPostXml(String url, String xmlBody)
throws
Exception{
String result =
""
;
HttpClient client =
new
HttpClient(
new
HttpClientParams(),
new
SimpleHttpConnectionManager(
true
));
client.getHttpConnectionManager().getParams().setConnectionTimeout(
15000
);
//通过网络与服务器建立连接的超时时间
client.getHttpConnectionManager().getParams().setSoTimeout(
60000
);
//Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
PostMethod method =
new
PostMethod(url);
method.setRequestHeader(
"Content-Type"
,
"application/xml"
);
if
(
null
!= xmlBody){
method.setRequestBody(xmlBody);
}
try
{
client.executeMethod(method);
result = method.getResponseBodyAsString();
}
catch
(Exception e) {
result =
"error"
;
logger.error(
"HTTP请求路径时错误:"
+ url, e.getMessage());
throw
e;
// 异常外抛
}
finally
{
if
(
null
!= method)
method.releaseConnection();
}
return
result;
}
URLConnection 的Post的请求:
public
static
String sendPost(String url, String param)
throws
Exception{
PrintWriter out =
null
;
BufferedReader in =
null
;
String result =
""
;
try
{
URL realUrl =
new
URL(url);
URLConnection conn = realUrl.openConnection();
conn.setConnectTimeout(
5000
);
conn.setReadTimeout(
10
*
1000
);
conn.setDoOutput(
true
);
// 发送POST请求必须设置如下两行
conn.setDoInput(
true
);
out =
new
PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in =
new
BufferedReader(
new
InputStreamReader(conn.getInputStream()));
String line;
while
((line = in.readLine()) !=
null
) {
result += line;
}
}
catch
(Exception e) {
logger.error(
"HTTP请求路径时错误:"
+ url, e.getMessage());
throw
e;
// 异常外抛
}
finally
{
try
{
if
(out!=
null
)out.close();
if
(in!=
null
) in.close();
}
catch
(Exception ex){
}
}
return
result;
}
另外还有一种HttpClient的请求方式,两者只是写法不一样而已。
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class ww {
// public static void main(String[] args) throws ClientProtocolException,
// IOException {
// String respContent = sendHttpGet();
// JSONObject result = JSONObject.fromObject(respContent);
// String success = result.getString("success");
// JSONObject date = result.getJSONObject("data");
// if (success=="true"||success.equals("true")){
// System.out.print(respContent);
// }else{
// JSONObject result = JSONObject.fromObject(respContent);
// JSONArray aa = result.getJSONArray("data");
// JSONObject gg = (JSONObject) aa.get(0);
//;
// System.out.print(gg.getString("fullName"));
// }
// }
public static String sendHttpGet() throws ClientProtocolException, IOException{
String strResult = null;
StringBuffer paramBuff = new StringBuffer("");
String newUrl = "http://localhost:8080/hssf/";
// 发送请求
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet request = new HttpGet(newUrl);
// request.setHeader("_csrf_header","X-CSRF-TOKEN");
// request.setHeader("_csrf","bf5131e5-63c3-44da-8d65-26bfb5bd38de");
CloseableHttpResponse httpResponse = httpclient.execute(request);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
//取得返回的字符串
strResult = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
}
else
{
System.err.print("请求错误!");
}
return strResult;
}
public static String sendHttpr(String weChat, String content)
throws ClientProtocolException, IOException {
String strResult = null;
// 使用NameValuePair来保存要传递的Post参数
// String sign = content.substring(0, 1);
// String meg = content.substring(1, content.length());
// Map<String,String> map = new HashMap<String, String>();
// map.put("FromUserName", "22452426");
// map.put("ToUserName", "22452426");
// map.put("Content", "T刘昊");
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加要传递的参数
params.add(new BasicNameValuePair("fromUserName", "de268"));
params.add(new BasicNameValuePair("toUserName", "de268"));
params.add(new BasicNameValuePair("content", "T刘昊"));
CloseableHttpClient httpclient = HttpClients.createDefault();
// HttpPost连接对象
HttpPost httpRequest = new HttpPost(
"http://10.44.111.122:8080/WeChatRobot/weChatManager/wxText");
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 请求httpRequest
httpRequest.setEntity(httpentity);
// 发送请求
CloseableHttpResponse httpResponse = httpclient.execute(httpRequest);
// 设置请求的参数 超时时间
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字符串
strResult = EntityUtils.toString(httpResponse.getEntity(),
HTTP.UTF_8);
} else {
System.err.print("请求错误!");
}
return strResult;
}
public static String sendHttpPost(String weChat, String content)
throws ClientProtocolException, IOException {
String strResult = null;
// 使用NameValuePair来保存要传递的Post参数
String sign = content.substring(0, 1);
String meg = content.substring(1, content.length());
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加要传递的参数
params.add(new BasicNameValuePair("weChat", weChat));
params.add(new BasicNameValuePair("sign", sign));
params.add(new BasicNameValuePair("fullName", meg));
params.add(new BasicNameValuePair("content", content));
CloseableHttpClient httpclient = HttpClients.createDefault();
// HttpPost连接对象
HttpPost httpRequest = new HttpPost(
"http://10.44.111.122:8080/weChat/weChatManager/wxText");
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 请求httpRequest
httpRequest.setEntity(httpentity);
// 发送请求
CloseableHttpResponse httpResponse = httpclient.execute(httpRequest);
// 设置请求的参数 超时时间
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字符串
strResult = EntityUtils.toString(httpResponse.getEntity(),
HTTP.UTF_8);
} else {
System.err.print("请求错误!");
}
return strResult;
}
/**
*
*
*/
public static String searchUserResult(String weChat, String meg)
throws ClientProtocolException, IOException {
String strResult = null;
// 使用NameValuePair来保存要传递的Post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加要传递的参数
params.add(new BasicNameValuePair("weChat", "3353677656"));
params.add(new BasicNameValuePair("fullName", "何镇镇"));
CloseableHttpClient httpclient = HttpClients.createDefault();
// HttpPost连接对象
HttpPost httpRequest = new HttpPost(
"http://10.44.111.122:8080/Contact/weChat/wxGetuser");
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 请求httpRequest
httpRequest.setEntity(httpentity);
// 发送请求
CloseableHttpResponse httpResponse = httpclient.execute(httpRequest);
// 设置请求的参数 超时时间
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字符串
strResult = EntityUtils.toString(httpResponse.getEntity(),
HTTP.UTF_8);
} else {
System.err.print("请求错误!");
}
System.out.print("2222222+++++++++++++++++_________++++_______");
return strResult;
}
}
http://www.javacui.com/java/359.html
http://javacui.com/opensource/322.html
http://www.cnblogs.com/langtianya/p/4001499.html
这几个网站比较来看比较容易理解
至于服务器端就用Spring来实现就行。