首页 > 代码库 > HttpURLConnection实现两个服务端的对接
HttpURLConnection实现两个服务端的对接
在企业开发中,很多时候需要用到两个服务端的对接,在java类中进行连接并传递参数,其中的HttpURLConnection是一种轻量化,并且简单的方法!
package httptest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
/*
* 请求类,分为post和get两个方法
*/
public class HttpClientHandle {
private static int HttpTimeOut = 20000; // 连接超时时间
private static String Method_Get = "GET"; // get方式
private static String Method_Post = "POST"; // post方式
public static void main(String[] args) {
Map<String, Object> fieldMap =new HashMap<String, Object>();
fieldMap.put("result","8888");
fieldMap.put("rest","888");
JSONObject jsonObject = JSONObject.fromObject(fieldMap);
String msg = new HttpClientHandle().post(jsonObject.toString(),"http://localhost:8080/SSM/teacher/insert");
//get方法
//String msg = new HttpClientHandle().get("","http://localhost:8080/SSM/teacher/update/10101542452425");
System.out.println(msg);
}
/**
*
* @param xmlmsg
* @param ServerUrl
* @param method
* @return
*/
public String sendHttpXML(String xmlmsg, String ServerUrl, String method) {
OutputStream out = null;
BufferedReader rs = null;
try {
// 1、建立连接
URL url = new URL(ServerUrl);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setReadTimeout(HttpTimeOut);
urlcon.setConnectTimeout(HttpTimeOut);
urlcon.setDoOutput(true);
urlcon.setDoInput(true);
urlcon.setRequestMethod(method);
//一定要设置 Content-Type 要不然服务端接收不到参数
urlcon.setRequestProperty("Content-Type", "application/Json;charset=UTF-8");
// 2、发送消息
if(Method_Post.equals(method) && !"".equals(xmlmsg)) {
out = urlcon.getOutputStream();
//Log.debug("==================sendHttpXML: " + xmlmsg);
out.write(xmlmsg.getBytes("UTF-8"));
out.flush();
}
urlcon.connect();
// 3、接收消息
rs = new BufferedReader(new InputStreamReader(urlcon.getInputStream(),"UTF-8"));
String line = rs.readLine();
StringBuffer str = new StringBuffer();
while(null != line) {
str.append(line);
line = rs.readLine();
}
//Log.debug("==================return xml" + str.toString());
return str.toString();
} catch (IOException e) {
//Log.infoStackTrace(e);
return null;
} catch (Exception e) {
//Log.infoStackTrace(e);
return null;
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (IOException e) {
//Log.warnStackTrace(e);
}
}
if (out != null) {
try {
out.close();
out = null;
} catch (IOException e) {
//Log.warnStackTrace(e);
}
}
}
}
/**
* POST方式请求
* @param xmlmsg
* @param ServerUrl
* @return
*/
public String post(String xmlmsg, String ServerUrl) {
return sendHttpXML(xmlmsg, ServerUrl, Method_Post);
}
/**
* GET方式请求
* @param xmlmsg
* @param ServerUrl
* @return
*/
public String get(String xmlmsg, String ServerUrl) {
return sendHttpXML(xmlmsg, ServerUrl, Method_Get);
}
}
--------------------------------------------------接收方法------------------------
//Post
@RequestMapping("/insert")
public String toAddTeacherPage(HttpServletRequest request ) throws Exception {
InputStreamReader reader=new InputStreamReader(request.getInputStream());
BufferedReader buffer=new BufferedReader(reader);
String data=http://www.mamicode.com/buffer.readLine();
System.out.println(data);
return "insert";
}
//Get
@RequestMapping(value="http://www.mamicode.com/update/{id}")
public ModelAndView updateById(@PathVariable("id") String id){
System.out.println(id);
return new ModelAndView("update");
}
本文属于原创,转载请注明出处。
HttpURLConnection实现两个服务端的对接