HttpURLConnection实现两个服务端的对接
Posted 技术记录
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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=buffer.readLine();
System.out.println(data);
return "insert";
}
//Get
@RequestMapping(value="/update/{id}")
public ModelAndView updateById(@PathVariable("id") String id){
System.out.println(id);
return new ModelAndView("update");
}
本文属于原创,转载请注明出处。
以上是关于HttpURLConnection实现两个服务端的对接的主要内容,如果未能解决你的问题,请参考以下文章
android中的HttpUrlConnection的使用之五
Android(或者Java)通过HttpUrlConnection向SpringMVC请求数据(数据绑定)
java用户HTTPURLConnection 上传文件过程是先把文件写入流中,然后上传吗,可以边度边传吗?
Android开发之下载服务器上的一张图片到本地java代码实现HttpURLConnection