说明
进行微信开发,后台程序需要与微信服务器进行交互,通过调用接口来完成服务,阅读微信开发文档,发现接口的调用都是通过http请求进行的,所以必须有个HttpUtil来支撑,这里总结下以javaAPI的方式和以Apach的HttpClient的方式进行HTTP请求
正文
使用java的HttpURLConnection
一个方法实现GET,POST请求
public static String httpRequest(String requestUrl, String requestMethod, String outputStr){
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod(requestMethod);
if("GET".equalsIgnoreCase(requestMethod)){
httpURLConnection.connect();
}
if(null != outputStr){
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(outputStr.getBytes("utf-8"));
outputStream.close();
}
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while((str = bufferedReader.readLine())!= null){
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
此方法通过指定URL,请求的方式和参数进行请求,使用流的方式发送参数和读取响应结果。该方法简单,没有设置http的请求属性等,示例代码在微信开发中可以实现功能。
在此方法中 参数outputStr是向微信服务器发送的json格式的数据或者xml结构的数据,友好性不太好,通常应该传递Map<String,Object> params 保存参数
Get请求
private static final String CHAR_SET = "UTF-8";
public static String sendGet(String url, Map<String,Object> params){
StringBuilder responseStr = null;
StringBuilder paramsStr = new StringBuilder();
if(params != null || params.size() > 0){
for(Map.Entry<String,Object> entry : params.entrySet()){
paramsStr.append(entry.getKey());
paramsStr.append("=");
try {
paramsStr.append(URLEncoder.encode(String.valueOf(entry.getValue()),CHAR_SET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
paramsStr.append("&");
}
}
URL URLstr = null;
BufferedReader bufr = null;
HttpURLConnection httpURLConnection = null;
try {
if(paramsStr != null && paramsStr.length() > 0){
url = url + "?" + paramsStr.substring(0,paramsStr.length() - 1);
}
URLstr = new URL(url);
httpURLConnection = (HttpURLConnection) URLstr.openConnection();
httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpURLConnection.connect();
responseStr = new StringBuilder();
bufr = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),CHAR_SET));
String str = null;
while((str = bufr.readLine()) != null){
responseStr.append(str);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
httpURLConnection.disconnect();
if (bufr != null){
try {
bufr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseStr.toString();
}
Post请求
public static String sendPost(String url, Map<String, Object> params){
StringBuilder responseStr = null;
StringBuilder paramsStr = new StringBuilder();
if(params != null || params.size() > 0){
for(Map.Entry<String,Object> entry : params.entrySet()){
paramsStr.append(entry.getKey());
paramsStr.append("=");
try {
paramsStr.append(URLEncoder.encode(String.valueOf(entry.getValue()),CHAR_SET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
paramsStr.append("&");
}
}
URL URLstr = null;
BufferedReader bufr = null;
HttpURLConnection httpURLConnection = null;
OutputStreamWriter osw = null;
try {
URLstr = new URL(url);
httpURLConnection = (HttpURLConnection) URLstr.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
if(paramsStr != null && paramsStr.length() > 0){
osw = new OutputStreamWriter(httpURLConnection.getOutputStream(),CHAR_SET);
osw.write(paramsStr.substring(0,paramsStr.length() - 1));
osw.flush();
}
bufr = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),CHAR_SET));
String str = null;
while((str = bufr.readLine()) != null){
responseStr.append(str);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(osw != null){
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpURLConnection != null) {
httpURLConnection.disconnect();
}
if(bufr != null){
try {
bufr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseStr.toString();
}
通过对比sendGet和sendPost两种方法,发现不同之处有:
- 在创建URL对象时,sendGet方法的url是直接拼接了参数,而sendPost方法没有,sendPost方法通过OutputStremWriter对象将参数直接写出
- 在创建了HttpURLConnection对象后,sendGet方法调用了connect()方法,sendPost没有调用此方法,但是显示设置了RequestMethod为POST
- 在设置参数sendGet方法显示设置了“Content-Type”,sendPost则省略了,该参数可以不显示设置,关于“application/x-www-form-urlencoded”详细解释,为什么可以不显示设置,详见:《HTTP中application/x-www-form-urlencoded字符说明》
- 在sendPost方法中显示设置了DoOutput和DoInput为true,UseCaches为false
使用HttpClient
Get请求
public static String httpClienOfGet(String url,Map<String,Object> params){
String res = "";
StringBuilder paramsStr = null;
if(params != null && params.size() > 0){
for(Map.Entry<String,Object> entry : params.entrySet()){
paramsStr.append(entry.getKey());
paramsStr.append("=");
try {
paramsStr.append(URLEncoder.encode(String.valueOf(entry.getValue()),CHAR_SET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
paramsStr.append("&");
}
}
if(paramsStr != null && paramsStr.length() > 0){
url = url + "?" + paramsStr.substring(0,paramsStr.length() - 1);
}
HttpGet httpGet = new HttpGet(url);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
res = EntityUtils.toString(response.getEntity());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return res;
}
Post请求
public static String httpClientOfPost(String url, Map<String, Object> params){
String res = "";
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
if(params != null && params.size() > 0){
for(Map.Entry<String,Object> entry : params.entrySet()){
paramList.add(new BasicNameValuePair(entry.getKey(),String.valueOf(entry.getValue())));
}
}
try {
if(paramList.size() > 0){
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList,CHAR_SET);
httpPost.setEntity(urlEncodedFormEntity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
res = EntityUtils.toString(response.getEntity());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return res;
}
通过比较这两种方式,发现在创建请求方法时,对url处理不同,HttpGet的url直接拼接了参数,而HttpGet的url不做处理,参数则是通过了urlEncodedFormEntity 对象进行设置
通过Post请求发送接收json格式的数据
在微信开发时,通常要通过http发送json格式的数据,微信服务器返回的是json数据,包含了code和msg
public static String jsonOfPost(String url, String param){
String res = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept","application/json");
httpPost.setHeader("Content-Type","application/json");
String charSet = "UTF-8";
HttpResponse response = null;
try {
StringEntity entity = new StringEntity(param,charSet);
entity.setContentEncoding(charSet);
entity.setContentType("application/json");
httpPost.setEntity(entity);
response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int state = statusLine.getStatusCode();
if(state == org.apache.http.HttpStatus.SC_OK){
HttpEntity responseEntity = response.getEntity();
res = EntityUtils.toString(responseEntity);
return res;
}else{
System.out.println("请求出错");
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
关于http的请求总结到这里,有关于POST和GET请求的区别,详见:
https://blog.csdn.net/yaojianyou/article/details/1720913/
http://www.nowamagic.net/librarys/veda/detail/1919
参考的优秀博文:
https://www.cnblogs.com/mengrennwpu/p/6418114.html
https://blog.csdn.net/u010197591/article/details/51441399
https://blog.csdn.net/qq9808/article/details/78320816