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");
}

 

 

本文屬於原創,轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM