<返回更多

使用java开发微信公众号系列-公共类

2021-06-16  今日头条  java浮萍
加入收藏
使用java开发微信公众号系列-公共类

 

 

在开发微信公众号时,需要不时请求URL和数据封装。为了不做重复的工作。提取公共部分进行封装。产生了相应的公众类。今天先来写下请求类,代码如下:

public class HttpRequestProxy {

/**

* 连接超时

*/

private static int connectTimeOut = 5000;

/**

* 读取数据超时

*/

private static int readTimeOut = 10000;

/**

* 发送GET的HTTP请求

* @param reqUrl HTTP请求URL

* @param parameters 参数映射表

* @param recvEncoding 请求编码

* @return HTTP响应的字符串

*/

public static String doGet(String reqUrl, Map<String,String> parameters,

String recvEncoding) {

HttpURLConnection url_con = null;

String responseContent = null;

try {

 

//请求URL的封装

url_con = doHttpGetConnection(reqUrl,parameters);

InputStream in = url_con.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(in,

recvEncoding));

String tempLine = rd.readLine();

StringBuffer temp = new StringBuffer();

String crlf = System.getProperty("line.separator");

while (tempLine != null) {

temp.Append(tempLine);

temp.append(crlf);

tempLine = rd.readLine();

}

responseContent = temp.toString();

rd.close();

in.close();

} catch (IOException e) {

 

} finally {

if (url_con != null) {

url_con.disconnect();

}

}

return responseContent;

}

/**

* 请求URL的封装

* @param reqUrl HTTP请求URL

* @param parameters 参数映射表

* @return URL的封装

* @throws IOException

*/

private static HttpURLConnection doHttpGetConnection(String reqUrl,

Map<String,String> parameters) throws IOException {

HttpURLConnection url_con = null;

String params = getMapParamsToStr(parameters,WeiXinConstant.REQUEST_ENCODING);

 

URL url = new URL(reqUrl);

url_con = (HttpURLConnection) url.openConnection();

url_con.setRequestMethod(WeiXinConstant.REQUEST_GET);

url_con.setConnectTimeout(
HttpRequestProxy.connectTimeOut);// (单位:毫秒)

url_con.setReadTimeout(
HttpRequestProxy.readTimeOut);// (单位:毫秒)

 

url_con.setDoOutput(true);

OutputStreamWriter out = new OutputStreamWriter(url_con.getOutputStream(),WeiXinConstant.REQUEST_ENCODING);

out.write(params);

out.flush();

out.close();

 

return url_con;

}

/**

* 发送POST的HTTP请求

*

* @param reqUrl HTTP请求URL

* @param parameters 参数映射表

* @param recvEncoding

* @return HTTP响应的字符串

*/

public static String doPost(String reqUrl, Map<String, String> parameters, String recvEncoding) {

HttpURLConnection url_con = null;

String responseContent = null;

try {

URL url = new URL(reqUrl);

url_con = (HttpURLConnection) url.openConnection();

url_con.setConnectTimeout(
HttpRequestProxy.connectTimeOut);// (单位:毫秒)

url_con.setReadTimeout(
HttpRequestProxy.readTimeOut);// (单位:毫秒)

url_con.setRequestMethod(WeiXinConstant.REQUEST_POST);

if (parameters!=null) {

url_con.setDoOutput(true);

String params = getMapParamsToStr(parameters, WeiXinConstant.REQUEST_ENCODING);

OutputStreamWriter out = new OutputStreamWriter(url_con.getOutputStream(),

WeiXinConstant.REQUEST_ENCODING);

out.write(params);

out.flush();

out.close();

}

InputStream in = url_con.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(in, recvEncoding));

String tempLine = rd.readLine();

StringBuffer tempStr = new StringBuffer();

String crlf = System.getProperty("line.separator");

while (tempLine != null) {

tempStr.append(tempLine);

tempStr.append(crlf);

tempLine = rd.readLine();

}

responseContent = tempStr.toString();

rd.close();

in.close();

} catch (IOException e) {

 

} finally {

if (url_con != null) {

url_con.disconnect();

}

}

return responseContent;

}

/**

* 发送POST的JSON HTTP请求

*

* @param reqUrl HTTP请求URL

* @param parameters 参数映射表

* @param recvEncoding

* @return HTTP响应的字符串

*/

public static String doJsonPost(String reqUrl, Map<String, String> parameters, String jsonData) {

HttpURLConnection url_con = null;

String responseContent = null;

try {

String params = getMapParamsToStr(parameters, WeiXinConstant.REQUEST_ENCODING);

URL url = new URL(reqUrl + "&" + params);

url_con = (HttpURLConnection) url.openConnection();

url_con.setRequestMethod(WeiXinConstant.REQUEST_POST);

url_con.setConnectTimeout(
HttpRequestProxy.connectTimeOut);// (单位:毫秒)

url_con.setReadTimeout(
HttpRequestProxy.readTimeOut);// (单位:毫秒)

url_con.setDoOutput(true);


url_con.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式


url_con.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式

OutputStreamWriter out = new OutputStreamWriter(url_con.getOutputStream(), WeiXinConstant.REQUEST_ENCODING);

out.write(jsonData);

out.flush();

out.close();

InputStream in = url_con.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(in, WeiXinConstant.REQUEST_ENCODING));

String tempLine = rd.readLine();

StringBuffer tempStr = new StringBuffer();

String crlf = System.getProperty("line.separator");

while (tempLine != null) {

tempStr.append(tempLine);

tempStr.append(crlf);

tempLine = rd.readLine();

}

responseContent = tempStr.toString();

rd.close();

in.close();

} catch (IOException e) {

 

} finally {

if (url_con != null) {

url_con.disconnect();

}

}

return responseContent;

}

/**

* post 文件的封装

* @param reqUrl HTTP请求URL

* @param parameters 参数映射表

* @param encoding 编码

* @param fileIn 数据流

* @param file 文件

* @param contentType 传输类型

* @param name 传输名称

* @return 响应结果

*/

public static String uploadMedia(String reqUrl, Map<String, String> parameters, String encoding,

InputStream fileIn, File file, String contentType,String name) {

HttpURLConnection url_con = null;

String responseContent = null;

try {

// 设置边界

String BOUNDARY = "----------" + System.currentTimeMillis();

String params = getMapParamsToStr(parameters, WeiXinConstant.REQUEST_ENCODING);

URL urlObj = new URL(reqUrl + "&" + params.toString());

// 连接

url_con = (HttpURLConnection) urlObj.openConnection();

/**

* 设置关键值

*/

url_con.setRequestMethod(
WeiXinConstant.REQUEST_POST); // 以Post方式提交表单,默认get方式

url_con.setDoInput(true);

url_con.setDoOutput(true);

url_con.setUseCaches(false); // post方式不能使用缓存

// 设置请求头信息

url_con.setRequestProperty("Connection", "Keep-Alive");

url_con.setRequestProperty("Charset", encoding);

// 设置边界

url_con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

// 请求正文信息

// 第一部分:

StringBuilder sb = new StringBuilder();

sb.append("--"); // 必须多两道线

sb.append(BOUNDARY);

sb.append("rn");

sb.append("Content-Disposition: form-data;name=""+name+"";filelength="" + file.length() + "";filename=""

+ file.getName() + ""rn");

sb.append("Content-Type:application/octet-streamrnrn");

byte[] head = sb.toString().getBytes(encoding);

// 获得输出流

OutputStream out = new DataOutputStream(url_con.getOutputStream());

// 输出表头

out.write(head);

// 文件正文部分

// 把文件已流文件的方式 推入到url中

DataInputStream in = new DataInputStream(fileIn);

int bytes = 0;

byte[] bufferOut = new byte[1024];

while ((bytes = in.read(bufferOut)) != -1) {

out.write(bufferOut, 0, bytes);

}

in.close();

// 结尾部分

byte[] foot = ("rn--" + BOUNDARY + "--rn").getBytes(encoding);// 定义最后数据分隔线

out.write(foot);

out.flush();

out.close();

InputStream iddn = url_con.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(iddn, encoding));

 

String tempLine = rd.readLine();

StringBuffer tempStr = new StringBuffer();

String crlf = System.getProperty("line.separator");

while (tempLine != null) {

tempStr.append(tempLine);

tempStr.append(crlf);

tempLine = rd.readLine();

}

responseContent = tempStr.toString();

rd.close();

} catch (IOException e) {

 

} finally {

if (url_con != null) {

url_con.disconnect();

}

}

return responseContent;

}

/**

* 将参数转换成string

*

* @param paramMap 参数映射表

* @param requestEncoding 编码

* @return

* @throws UnsupportedEncodingException

*/

private static String getMapParamsToStr(Map<String, String> paramMap, String requestEncoding) throws IOException {

StringBuffer params = new StringBuffer();

// 设置边界

Set<String> set = paramMap.keySet();

for (String key : set) {

params.append(key);

params.append("=");

params.append(URLEncoder.encode(paramMap.get(key), requestEncoding));

params.append("&");

}

if (params.length() > 0) {

params = params.deleteCharAt(params.length() - 1);

}

return params.toString();

}

}

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>