使用HttpURLConnection调用url方式访问spring mvc中的controller并传json值与返回
1.目标:使用HttpURLConnection调用url方式访问spring mvc中的controller传入json值后返回结果。
2:HttpURLConnection调用url并传入参数controller层。
2.1 分别通过post 和get的方式传入url参数?lasttime=2017-01-16到controller调用相关业务层:
package com.zl.test2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
/**
*
* @author zenglong
*
* @Description: HttpURLConnection 方式推接口平台
*
*/
public class HttpUrlGet {
static String proxyHost = "127.0.0.1";//ip地址
static int proxyPort = 8080;//端口
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param isproxy
* 是否使用代理模式
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param,boolean isproxy) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = null;
if(isproxy){//使用代理模式
@SuppressWarnings("static-access")
Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
conn = (HttpURLConnection) realUrl.openConnection(proxy);
}else{
conn = (HttpURLConnection) realUrl.openConnection();
}
// 打开和URL之间的连接
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST"); // POST方法
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.setDoOutput(true);
connection.connect();
// 获取所有响应头字段
// Map<String, List<String>> map = connection.getHeaderFields();
// // 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
/**
* post 方式到平台查数据
*/
String url = "http://127.0.0.1:8080/abs/getProgressinfo";
String para = "lasttime=2017-01-16";
String sr=HttpUrlGet.sendPost(url,para,true);
/**
* get 方式到平台查数据
*/
// String url2 = "http://127.0.0.1:8080/abs/getProgressinfo";
// String para2 = "lasttime=2017-01-16";
// String sr=HttpUrlGet.sendGet(url2,para2);
System.out.println(sr);
}
}
2.2:controller接收
/**
* 前海调用进度款申请表
* @return
* @throws IOException
*/
@RequestMapping(value = "/getProgressinfo")
public void getProgressinfo(HttpServletResponse response,HttpServletRequest request) throws IOException {
responseUtil(response);
String lasttime=(String) request.getParameter("lasttime");
System.out.println("lasttime为:====="+lasttime);
if (lasttime!=null && lasttime.trim().length()>0) {
List<ProgressinfoEntity> res = proService.getProgressinfo(lasttime);
ObjectMapper mapper=new ObjectMapper();
String jsonStr = mapper.writeValueAsString(res);
response.getWriter().write(jsonStr);
}else {
response.getWriter().write("failed");
}
}
3:
分别通过post 和get的方式传入json
到controller调用相关业务层:
package com.zl.test2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import com.zl.test1.HttpRequestUtil;
/**
*
* @author zenglong
*
* @Description: 往接口平台推送json数据
*
*/
public class HttpUrlSend {
static String proxyHost = "127.0.0.1";
static int proxyPort = 8080;
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
// String urlNameString = url + "?" + param;
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.setDoOutput(true);
connection.connect();
// 获取所有响应头字段
// Map<String, List<String>> map = connection.getHeaderFields();
// // 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
String jsonStr="{"
+ "\"bgyprogressuuid\": \"aabc891fc62f41728497da2904294e29\","
+ "\"bgysupplier\": \"供应商名称3\","
+ " \"bgyitemname\": \"项目公司名称3\","
+ "\"bgyitemcode\": \"0003\","
+ "\"bgyarea\": \"佛山区域3\","
+ "\"bgycontractname\": \"合同名称\","
+ "\"bgycontractno\": \"合同编号003\","
+ "\"bgypayamount\": 888.989,"
+ "\"bgysupplierbank\": \"供应商开户行:中国银行\","
+ "\"bgysupplieraccount\": \"供应商账号:88888989989\","
+ "\"bgysupplieraccountname\": \"收方户名:佛山碧桂园\","
+ "\"bgypaystatus\": false,"
+ "\"dr\": 0}";
OutputStream out = connection.getOutputStream();
// 写入请求的字符串
out.write((jsonStr.toString()).getBytes());
out.flush();
out.close();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param isproxy
* 是否使用代理模式
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param,boolean isproxy) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = null;
if(isproxy){//使用代理模式
@SuppressWarnings("static-access")
Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
conn = (HttpURLConnection) realUrl.openConnection(proxy);
}else{
conn = (HttpURLConnection) realUrl.openConnection();
}
// 打开和URL之间的连接
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST"); // POST方法
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
String jsonStr="{"
+ "\"bgyprogressuuid\": \"aabc891fc62f41728497da2904294e29\","
+ "\"bgysupplier\": \"供应商名称3\","
+ " \"bgyitemname\": \"项目公司名称3\","
+ "\"bgyitemcode\": \"0003\","
+ "\"bgyarea\": \"佛山区域3\","
+ "\"bgycontractname\": \"合同名称\","
+ "\"bgycontractno\": \"合同编号003\","
+ "\"bgypayamount\": 888.989,"
+ "\"bgysupplierbank\": \"供应商开户行:中国银行\","
+ "\"bgysupplieraccount\": \"供应商账号:88888989989\","
+ "\"bgysupplieraccountname\": \"收方户名:佛山碧桂园\","
+ "\"bgypaystatus\": false,"
+ "\"dr\": 0}";
// 发送请求参数
out.write(jsonStr);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
/**
* post 方式推数据到平台
*/
String url = "http://127.0.0.1:8080/abs/sendProgressinfo";
String para = "";
String sr=HttpUrlSend.sendPost(url,para,true);
/**
* get 方式推数据到平台
*/
// String url2 = "http://127.0.0.1:8080/abs/sendProgressinfo";
// String para2 = "";
// String sr=HttpUrlSend.sendGet(url2,para2);
System.out.println(sr);
}
}
3.1 controller中读取json数据并进行相关操作:
/**
* 明源推数据到平台
* @return
* @throws IOException
*/
@RequestMapping(value = "/sendProgressinfo")
public void sendProgressinfo(HttpServletResponse response,HttpServletRequest request) throws IOException {
responseUtil(response);
String paramString = null;
StringBuffer bfBuffer = new StringBuffer();
InputStream is = request.getInputStream();
InputStreamReader reader = new InputStreamReader(is,"utf-8");
BufferedReader br = new BufferedReader(reader);
while((paramString=br.readLine())!=null)
{
bfBuffer.append(paramString);
}
String jsonStr=bfBuffer.toString();
// ProgressinfoEntity proEntity=new ProgressinfoEntity
// ("aabc891fc62f41728497da2904294e28","供应商名称2","项目公司名称2","002","佛山区域2",
// "合同名称","合同编号002",888.989,"供应商开户行:中国银行2","供应商账号2:88888989989","收方户名:佛山碧桂园",false,"2017-01-18 20:18:09");
// @SuppressWarnings("unchecked")
// List<ProgressinfoEntity> proEntity = (List<ProgressinfoEntity>) mapper.readValue(json, ProgressinfoEntity.class);
ObjectMapper mapper=new ObjectMapper();
if (jsonStr!=null && jsonStr.trim().length()>0) {
ProgressinfoEntity proEntity = mapper.readValue(jsonStr, ProgressinfoEntity.class);//一条
proEntity.setLasttime(DateUtil.formatDate());
ProgressinfoEntity s = proService.sendProgressinfo(proEntity);
response.getWriter().write("secceed");
}else {
response.getWriter().write("failed");
}
}
源代码下载地址:
http://download.csdn.net/detail/qq_31968809/9776026