最近项目的一个模块,需要调用另一个项目的接口, 找到以前写的java调用http接口的,发现太粗略了,就扒了扒网上诸大神的笔记,整理了一份进阶版的代码,方便以后使用。如果不合理的地方,忘指教,共同学习,共同进步!废话不多说,直接上代码。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.com.easy.annotation.Controller;
import cn.com.easy.core.sql.SqlRunner;
import net.sf.json.JSONObject;

/**
 * @Title: HttpTestAction.java
 * @Package 
 * @Description: java调用http接口
 * @version V1.0
 */
public class HttpTestAction{
	private static SqlRunner runner;
	private static final Log LOG = LogFactory.getLog(HttpTestAction.class);
	
	public static JSONObject load(String url,String data){
		String encoding = "UTF-8";
	    HttpURLConnection httpConnection = null;
	    PrintWriter printWriter = null;//
        StringBuilder stringBuilder = new StringBuilder(); // 用来存储响应数据
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        JSONObject resultJson = null;
		try {

            URL targetUrl = new URL(url);
            // 新建链接实例
            httpConnection = (HttpURLConnection) targetUrl.openConnection();
            // 设置链接超时时间,单位毫秒
            httpConnection.setConnectTimeout(2000);
            // 设置读取数据超时时间,单位毫秒
            httpConnection.setReadTimeout(2000);
            // 是否打开输出流true|false
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            // 设置提交方法 POST|GET
            httpConnection.setRequestMethod("POST");
            // 是否使用缓存true|false
            httpConnection.setUseCaches(false);
            httpConnection.setRequestProperty("Accept-Charset", encoding);
            // 标准的HTTP POST是一种application/x-www-form-urlencoded 类型的网络表单,传递的参数都会被写入请求信息主体中
            // httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset="+encoding);
            httpConnection.setRequestProperty("Content-Type", "application/json");
            
            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            httpConnection.connect();

            //获取URLConnection对象对应的输出流
            printWriter = new PrintWriter(httpConnection.getOutputStream());
            //发送请求参数即数据
            printWriter.print(data);
            // 输出完成后刷新并关闭流
            printWriter.flush();
            printWriter.close();
            
            // 这里返回200,则是成功调用接口,否则失败
            if(httpConnection.getResponseCode()==200){
            	// 得到响应流
            	inputStream = httpConnection.getInputStream();
            	// 处理服务器响应  (将从连接获取到输入流包装为bufferedReader)
            	bufferedReader = new BufferedReader(new InputStreamReader(inputStream,encoding)); 
            	String line;
            	// 循环读取流,若不到结尾处
            	while ((line = bufferedReader.readLine()) != null) {
            		stringBuilder.append(line);
            	}
            	//关闭流
            	bufferedReader.close(); 
            	inputStream.close();
            }else{
            	stringBuilder.append("{\"success\":\"false\",\"message\":\"调用http接口失败!\"}");
            }
            
            // 关闭连接
            httpConnection.disconnect(); 
            // 转换成json对象
            resultJson = JSONObject.fromObject(stringBuilder.toString());
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(printWriter!=null){
				printWriter.close();
			}
			if(httpConnection!=null){
				httpConnection.disconnect();
			}
		}

        return resultJson;
	}
    /**
     * 这里是本人进行的调试,作为记录使用,仅供参考
     */
	public static void main(String[] args) throws Exception {

		// http接口地址
		String urlHead = "http://127.0.0.1:8089/bpm/bpmservice";
		// 流程模板编码
		String modelKey = "HR_INTEGRAL_EXCHANGEPLAN_APPLY";
		//String applyId = initApplyId();
		// 流程申请编码
		String applyId = "QJ-20190312105823001";
		// 流程发起人编码
		String loginId = "admin";
		// 流程接收人编码
		String staffCode = "10001";
		//URLEncoder.encode()方法  为字符串进行编码
		String userName = URLEncoder.encode("管理员","UTF-8");
					
		// 1:新建流程
		JSONObject result1 = load(urlHead+"/process/startProcessByModelKey?loginId="+loginId+"&modelKey="+modelKey,"{applyId:'"+applyId+"',userName:'"+userName+"',staffCode:'"+staffCode+"'}");
		System.out.println("processInstanceId:"+result1.get("processInstanceId"));
		if(result1.getString("success")=="true"){
			// 2:根据流程实例获取待办任务id
			JSONObject result2 = load(urlHead+"/worktask/getUserTaskByPId?loginId="+staffCode+"&processInstanceId="+result1.get("processInstanceId"),"");
			System.out.println("taskId:"+result2.get("taskId"));
			
			if(result2.getString("success")=="true"){
				// 3:根据流程id获取流程信息
				JSONObject result3 = load(urlHead+"/worktask/getTaskDealInfo?loginId="+staffCode+"&taskId="+result2.get("taskId"),"");
				String array = result3.getString("taskDealInfo");
				JSONObject result4 = JSONObject.fromObject(array);
				System.out.println("formUrl:"+result4.get("formUrl"));
				
				if(result4.getString("success")=="true"){
					// 4:拼接待办页面url
					String formUrl = result4.get("formUrl")+"?applyId="+applyId+"&flowInstId="+result1.get("processInstanceId")+"&taskId="+result2.get("taskId");
					System.out.println("待办页面url:"+formUrl);
				}
			}
		}
	}
	
	public static String initApplyId(){
		// 获取当前时间当做任务编码的sql
		String sql = runner.sql("hr.integralManagement.getSystem");
		Map<String, String> map;
		String applyId = "";
		try {
			map = runner.queryForMap(sql);
			if(map.get("APPLYID") != null&& !("").equals(map.get("APPLYID"))){
				applyId = "QJ-"+map.get("APPLYID");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return applyId;
		
	}
}

吐槽一下:HTML编辑器太不好用了,插入一段java代码,格式都乱了,调了几次,还是这样,明明编辑的时候格式也是对的,但是发布后就成了这个鬼样子,什么情况