Http定义了与服务器交互的不同方法,最基本的方法有4种,分别是GET,POST,PUT,DELETE。URL全称是资源描述符,我们可以这样认为:一个URL地址,它用于描述一个网络上的资源,而HTTP中的GET,POST,PUT,DELETE就对应着对这个资源的查,改,增,删4个操作。就我理解,GET一般用于获取/查询资源信息,而POST一般用于更新资源信息。
当然,并不是说get就只能请求数据而post就是发送数据,实际上两者都是想服务器发起请求,只是请求体封装的形式不一样,简答来说就是get方式是“”http://write.blog.csdn.net/postedit?ref=toolbar&ticket=ST-224386-4oSwsD9bbQe9azM4OGeI-passport.csdn.net”是可以直接将参数拼在url后面进行数据访问的,而post必须以输入输出流的形式将参数put进去的。话不多说,下面上代码比较两者的区别你们就能明白了。
现在我这边是调用第三方接口,所以需要建立HTTP连接,至于建立http连接有几种常用的方法我就暂时不介绍了,有机会会另外写一篇文章单独介绍建立网络请求的几种常用方式和代码展示的。现在就将get和post的区别,写的一个测试样例,还没有封装参数,如需封装(get post params urlConnection request response configuration等),请自行解决(现在网上有很多开源的第三方工具httpok、httpclient等都做得很不错)或者有意者私信我我可以给你。废话这么久开始上代码把。
这是我自己写的一个封装好的httpUtils类。
package cuc.miti.nms.httpUtil;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Test;
import com.alibaba.fastjson.JSONObject;
import cuc.miti.nms.util.MD5Util;
import cuc.miti.nms.util.PropertiesUtil;
public class HttpConnectUtil {
// private Logger logger = LoggerFactory.getLogger(getClass());
private int status;
private int id;
private String appid =""
private String secret = "";
@Test
public boolean updateCms(int rankStatus, int cms_id) {
status = rankStatus;
id = cms_id;
String jsonResult = makeUrl();
return encodeResult(jsonResult);
}
//解析response的state字段,如果是true则评审和更新同步
private boolean encodeResult(String result) {
JSONObject object =JSONObject.parseObject(result);
return object.getBooleanValue("state");
}
private String makeUrl() {
long time = System.currentTimeMillis();
// System.out.println("md5Data:" + md5Data);
String appId= PropertiesUtil.getProperty("cmsAppId");
String sign= PropertiesUtil.getProperty("cmsAppId");
String basePath = (String) PropertiesUtil.getProperty("cmsIp");
String url = basePath + "update?appid="+appId+"&sign="+sign
+ "&time=" + time;
String respone = getUpdate(url);
System.out.println("response:" + respone);
return respone;
}
//以get方式发送请求,拼接参数
public String getUpdate(String url) {
String responseMessage = "";
StringBuffer resposne_sb = new StringBuffer();
HttpURLConnection httpConnection = null;
DataOutputStream out = null;
BufferedReader reader = null;
String getUrl=url+"&status="+status+"&id="+id;
try {
URL urlGet = new URL(getUrl);
httpConnection = (HttpURLConnection) urlGet.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
// 参数长度太大,不能用get方式,一般会把这些参数统一封装成一个对象
//再用json解析出来
httpConnection.setRequestMethod("GET");
httpConnection.setUseCaches(false);// 不使用缓存
httpConnection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
httpConnection.setInstanceFollowRedirects(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数
httpConnection.setRequestProperty("Content-Type",
"application/octet-stream");
httpConnection.setRequestProperty("Charset", "UTF-8");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
// 实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
// logger.debug("打开连接:" + url);
httpConnection.connect();
// 获得响应状态
int resultCode = httpConnection.getResponseCode();
reader = new BufferedReader(new InputStreamReader(
httpConnection.getInputStream(), "UTF-8"));
if (HttpURLConnection.HTTP_OK == resultCode) {
while ((responseMessage = reader.readLine()) != null) {
resposne_sb.append(responseMessage);
}
// reader.close();
}
// 将该url的配置信息缓存起来
return resposne_sb.toString();
} catch (IOException e) {
System.out.println("连接失败,url={}" + url);
return "failed";
} finally {
try {
if (null != out) {
out.close();
}
if (null != reader) {
reader.close();
}
if (null != httpConnection) {
httpConnection.disconnect();
}
} catch (Exception e2) {
System.out.println("http connection close error:{}" + e2);
}
}
}
//以get方式发送请求,拼接参数
public String postUpdate(String url) {
// logger.info("=================开始获取信息,地址{}=================" , url);
String responseMessage = "";
StringBuffer resposne_sb = new StringBuffer();
HttpURLConnection httpConnection = null;
DataOutputStream out = null;
BufferedReader reader = null;
try {
URL urlGet = new URL(url);
httpConnection = (HttpURLConnection) urlGet.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
// 参数长度太大,不能用get方式,一般会把这些参数统一封装成一个对象
//再用json解析出来
httpConnection.setRequestMethod("POST");
httpConnection.setUseCaches(false);// 不使用缓存
httpConnection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
httpConnection.setInstanceFollowRedirects(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数
httpConnection.setRequestProperty("Content-Type",
"application/octet-stream");
httpConnection.setRequestProperty("Charset", "UTF-8");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
// 实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
// logger.debug("打开连接:" + url);
httpConnection.connect();
out = new DataOutputStream(httpConnection.getOutputStream());
// // The URL-encoded contend
// // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", id);
jsonObject.put("status", status);
// 写入post参数,DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.writeBytes(jsonObject.toJSONString());
System.out.println("请求参数:"+jsonObject.toJSONString());
// flush and close
out.flush();
out.close();
// 获得响应状态
int resultCode = httpConnection.getResponseCode();
reader = new BufferedReader(new InputStreamReader(
httpConnection.getInputStream(), "UTF-8"));
if (HttpURLConnection.HTTP_OK == resultCode) {
while ((responseMessage = reader.readLine()) != null) {
resposne_sb.append(responseMessage);
}
// reader.close();
}
if (!"failure".equals(resposne_sb.toString())) {
System.out.println("Success send to JMX");
} else {
System.out.println("failure send to JMX");
}
// 将该url的配置信息缓存起来
return resposne_sb.toString();
} catch (IOException e) {
System.out.println("连接失败,url={}" + url);
return "failed";
} finally {
try {
if (null != out) {
out.close();
}
if (null != reader) {
reader.close();
}
if (null != httpConnection) {
httpConnection.disconnect();
}
} catch (Exception e2) {
System.out.println("http connection close error:{}" + e2);
}
}
}
}