1、JSON值访问

/**
 * 调用对方接口方法
 * @param path 对方或第三方提供的路径
 * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
 */
public static void interfaceUtil(String path,String data) {
    try {
        URL url = new URL(path);
        //打开和url之间的连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求的方法类型
        conn.setRequestMethod("POST");
        //设置请求的内容类型
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        //设置发送数据
        conn.setDoOutput(true);
        //设置接受数据
        conn.setDoInput(true);
        //发送数据,使用输出流
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(data.getBytes("UTF-8"));
        //获取URLConnection对象对应的输入流
        InputStream is = conn.getInputStream();
        
        //构造一个字符流缓存
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str = "";
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
        String response = byteArrayOutputStream.toString();
        System.out.println(response);
        //关闭流
        is.close();
        //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
        //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
        conn.disconnect();
        System.out.println("完整结束");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

 

2、form表单形式提交key-value值访问

 

key-value值放进一个Map中

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;

/**
 * 调用对方接口方法
 * @author wxd
 */
public class InterfaceUtil {

    private static final Logger logger = Logger.getLogger(InterfaceUtil.class);
    
    private static final int REQUEST_SUCCESS = 200;
    
    /**
     * 调用对方接口方法
     * @param path 对方或第三方提供的路径
     * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
     */
    public static void postRequest(String path, Map<String,String> params) {
        OutputStream outputStream = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        URL url = null;
        try {
            // 拼接请求参数  
            StringBuffer sb = new StringBuffer(); 
            String sbRlt = null;
            if (params != null) {  
                for (Entry<String, String> e : params.entrySet()) {  
                    sb.append(e.getKey());  
                    sb.append("=");  
                    sb.append(e.getValue());  
                    sb.append("&");  
                }  
                sbRlt = sb.substring(0, sb.length() - 1);  
            }  
            url = new URL(path);
            //打开和url之间的连接
            conn = (HttpURLConnection) url.openConnection();
            
            //设置请求的方法类型
            conn.setRequestMethod("POST");
            //设置请求的内容类型
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            //设置发送数据
            conn.setDoOutput(true);
            //设置接受数据
            conn.setDoInput(true);
            //发送数据,使用输出流
            outputStream = conn.getOutputStream();
            outputStream.write(sbRlt.getBytes("UTF-8"));
            //获取URLConnection对象对应的输入流
            is = conn.getInputStream();
            if(conn.getResponseCode() == REQUEST_SUCCESS) {
                //构造一个字符流缓存
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String str = "";
                while ((str = br.readLine()) != null) {
                    logger.info(str);
                    System.out.println(str);
                }
            }else {
                logger.error("访问失败");
                System.out.println("访问失败");
            }
        } catch (Exception e) {
            logger.error("访问失败");
            e.printStackTrace();
        } finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                conn.disconnect();
            }
        }
    }
    
}

 

 posted on 2018-12-14 14:38  布鲁布鲁sky  阅读(3598)  评论(1编辑  收藏  举报