Java调用http保留访问状态

 

package com.coracle;

import com.coracle.yk.xframework.util.yunTongXun.HttpRequest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by huangbaidong
 * 2017/4/12.
 */
public class TestHttpStatus {

    public static void main(String[] args) throws Exception {
        try {
            //1、先登录获取SessionId也就是cookie
            String sessionId = login();
            //2、然后调用其他接口,带上cookie,
            String result = httpRequest("http://localhost:8083/xweb/api/v2/order/list", "{}", sessionId);
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 访问其他有权限控制的接口
     * @param url  自己传URL
     * @param json
     * @param sessionId
     * @return
     * @throws Exception
     */
    public static String httpRequest(String url, String json, String sessionId) throws Exception {
        // 使用POST方式向目的服务器发送请求
        URL connect;
        OutputStreamWriter paramout = null;
        BufferedReader reader = null;

        StringBuffer data = new StringBuffer();
        try {
            connect = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Cookie", sessionId);
            System.out.println("newSession:"+sessionId);
            paramout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            paramout.write(json);
            paramout.flush();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (paramout != null) {
                    paramout.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return data.toString();
    }


    /**
     * 登录获取session
     * @return
     * @throws IOException
     */
    public static String login() throws IOException {
        URL url = new URL("http://localhost:8083/xweb/api/v2/login/userLogin?loginName=positec&password=qwe123");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        String str = "url = " + url;
        out.println(str);
        out.flush();
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String destStr = "";
        String inputLin = "";
        while((inputLin = in.readLine()) != null ){
            destStr +=  inputLin;
        }
        System.out.println(destStr);
        String session_value = conn.getHeaderField("Set-Cookie");
        String[] sessionId = session_value.split(";");//第一登录,取出SESSIONID
        System.out.println("Session Value = " + session_value);
        return sessionId[0];
    }
}

 

posted @ 2017-04-27 10:52  旋转的梦  阅读(412)  评论(0编辑  收藏  举报