HTTP发送的数据有两种方式,一种是GET请求,一种是POST请求,GET请求就是简单的URL拼接参数,发送的参数长度也有限制。
而POST的参数可以设置在FORM中,参数长度也可以满足大多要求,有时从服务器的性能上考虑,防止恶意的GET尝试,很多接口都是限制POST方式的。
那么POST请求发送参数来说常用也有两种方式,一种是拼接参数和GET一样,但是发送方式指定为POST。
发送的数据不同,也可以在头上进行指定,这里的示例基于HttpClient。
这里也写个简单GET请求:
/**
* 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;
}
POST请求我们使用URLConnection来写:
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;
}
此时,同一个连接,调用不同的方法,就是不同的发送方式。
服务器端接收的话可以参照这样,基于SpringMVC的写法:
@SuppressWarnings({ "unchecked" })
@RequestMapping(value="/testPost2",method = RequestMethod.POST)
public ResponseEntity<String> testPost2(HttpServletRequest req,HttpServletResponse res,
@RequestParam(value="postXML") String postXML) throws Exception{
System.out.println(postXML);
Document docRe = DocumentHelper.createDocument();
Element SyncAppOrderResp = docRe.addElement("reXML").addNamespace("",
"http://www.javacui.com/xml/schemas/");
SyncAppOrderResp.addElement("status").addText("0");
return new ResponseEntity(docRe.asXML(), HttpStatus.OK);
}
以上的写法,POST的参数是基于KEY和VALUE方式的,还有一种普遍做法是把参数XML直接写在头里面。
此时的写法就是把要发送的参数写在RequestBody里面,执行发送的内容是基于什么格式的,例如下面的示例,普通发送,JSON和XML:
/**
* 普通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;
}
而服务器端接收时,就需要从头中获取参数,代码参考:
@SuppressWarnings({ "unchecked" })
@RequestMapping(value="/testPost1",method = RequestMethod.POST)
public ResponseEntity<String> testPost1(HttpServletRequest req,HttpServletResponse res)
throws Exception{
BufferedReader bufferReader = req.getReader();//获取头部参数信息
StringBuffer buffer = new StringBuffer();
String line = " ";
while ((line = bufferReader.readLine()) != null) {
buffer.append(line);
}
String postData = buffer.toString();
System.out.println(postData);
Document docRe = DocumentHelper.createDocument();
Element SyncAppOrderResp = docRe.addElement("reXML").addNamespace("",
"http://www.javacui.com/xml/schemas/");
SyncAppOrderResp.addElement("status").addText("0");
return new ResponseEntity(docRe.asXML(), HttpStatus.OK);
}
testPost1和testPost2这两种方式,我们可以写一个MAIN来测试:
public static void main(String[] args) {
try {
System.out.println(HttpPostXml("http://localhost:8008/api/testPost1",
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><root><status>1
</status></root>"));
System.out.println(sendPost("http://localhost:8008/api/testPost2",
"postXML=<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><root>
<status>1</status></root>"));
} catch (Exception e) {
e.printStackTrace();
}
}
发送接收的都是XML参数,发送和接收打印在控制台。
文章参考地址:java小强个人博客站点