【问题标题】:How to use Cookies in HttpURLConnection for ANDROID?如何在 ANDROID 的 HttpURLConnection 中使用 Cookie?
【发布时间】:2013-03-28 04:37:14
【问题描述】:

我正在尝试为 Asterisk 接口创建一个应用程序,配置设置已经正确完成,因为我已经仔细检查了它。

我无法从 Asterisk 服务器访问配置文件的原因似乎与连接有关。我需要使用 cookie 连接到登录会话的同一实例。

但到目前为止我无法正确使用 Cookie 需要一点帮助。

我应该通过按button1(bt1)登录并通过按button2(btn2)获取配置文件。

public class AsteriskInterface extends Activity {

    private static final String TAG = " AsteriskInterface";

    EditText ed1;
    Button bt1,bt2;
    static String url ="http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
    static String logincmd ="http://192.168.8.2:8088/asterisk/rawman?action=login&username=admin&secret=admin123";
    static String getfilecmd = "http://192.168.8.2:8088/asterisk/rawman?action=getconfig&filename=sip.conf";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ed1 = (EditText) this.findViewById(R.id.editText);
        bt1 = (Button) this.findViewById(R.id.submit);
        bt2 = (Button) this.findViewById(R.id.config);
        final WebView myWebView = (WebView) findViewById(R.id.webView);

        bt1.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                try{
                    new Execute().execute(logincmd);
                } catch(Exception e) {
                    Log.v("Exception execute", "Exception:"+e.getMessage());
                }           
            }
        });

        bt2.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {    
                try{
                    new Execute().execute(getfilecmd);
                } catch(Exception e) {
                    Log.v("Exception execute", "Exception:"+e.getMessage());
                }
                //myWebView.loadUrl(cmd2);
            }
        });
    }

    public static void Response(String result) {
        Log.e(TAG,result);  
    }
}

class Execute extends AsyncTask<String, Integer, String> {

    List<String> cookies = null;

    protected String doInBackground(String... searchKey) {

        String cmd = searchKey[0];
        try {
            return  action2(cmd);
        } catch(Exception e) {
            Log.v("Exception execute do back ground", "Exception:"+e.getMessage());
            return "";
        }
    }

    protected void onPostExecute(String result) {
        try {
            AsteriskInterface.Response(result);
        } catch(Exception e) {
            Log.v("Exception excecute onPost Execute",
                    "Exception:"+e.getMessage());
        }
    }

    private String action2(String uRL) throws MalformedURLException, IOException {

        StringBuilder response = new StringBuilder();
        Log.v("Execute","execute url:"+uRL);
        URL url = new URL(uRL);
        HttpURLConnection httpconn  = (HttpURLConnection) url.openConnection();

        DataOutputStream out;
        DataInputStream in;

        if(cookies==null){
            httpconn.getHeaderField("Set-Cookie");
        }
        if(cookies!=null){
            for(String cookie : cookies){
                httpconn.setRequestProperty("Cookie", cookie);
            }
        }
        httpconn.setDoOutput(true);
        String post = "mobile_app="+URLEncoder.encode("1","UTF-8");
        out = new DataOutputStream(httpconn.getOutputStream());
        out.writeBytes(post);
        out.flush();
        out.close();
        in = new DataInputStream(httpconn.getInputStream());
        String line = "";
        String data = "";
        while((line=in.readLine())!=null){
            data+=line;
        }

        if(httpconn.getResponseCode()==HttpURLConnection.HTTP_OK) {
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpconn.getInputStream()),
                    8192);
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();
        }
        return response.toString();
    }
}

我可以确定我正在连接到以前的登录会话。但是现在如何发出新的命令呢?

03-28 10:02:15.861: V/执行(4261): 执行 url:http://192.168.8.x:8088/asterisk/rawman?action=login&username=admin&secret=admin123 03-28 10:02:18.871: V/Exception 执行做后台(4261): 例外:已经连接 03-28 10:02:23.651: V/Execute(4261): 执行 网址:http://192.168.8.x:8088/asterisk/rawman?action=getconfig&filename=sip.conf 03-28 10:02:26.691:V/异常执行做背景(4261): 例外:已经连接 03-28 10:02:26.721: D/dalvikvm(4261): GC_CONCURRENT 释放 226K,8% 释放 7430K/8007K,暂停 24ms+3ms,总计 61毫秒

【问题讨论】:

    标签: android session-cookies httpurlconnection httpcookie asteriskami


    【解决方案1】:
    private String action(String uRL)
                throws MalformedURLException, IOException {
    
            StringBuilder response = new StringBuilder();
            Log.v("Execute","execute url:"+uRL);
            URL url = new URL(uRL);
            HttpURLConnection httpconn  = (HttpURLConnection) url.openConnection();
    
            if(sCookie!=null && sCookie.length()>0){
                httpconn.setRequestProperty("Cookie", sCookie);
            }
    
            if(httpconn.getResponseCode()==HttpURLConnection.HTTP_OK) {
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(httpconn.getInputStream()),
                        8192);
                String strLine = null;
                while ((strLine = input.readLine()) != null) {
                    response.append(strLine);
                }
                input.close();
            }
    
            String cookie = httpconn.getHeaderField("set-cookie");
            if(cookie!=null && cookie.length()>0){
                sCookie = cookie;
            }
            return response.toString();
    
        }
    

    【讨论】:

    • sCookie 是静态的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 2018-06-01
    • 2015-01-01
    • 2013-04-15
    • 1970-01-01
    • 2019-09-26
    • 2012-09-03
    相关资源
    最近更新 更多