(Android App)如何使用Cookie验证我的帖子请求?

时间:2015-11-05 05:38:00

标签: android http authentication cookies request

那么, 我正在创建一个需要发帖请求的Android应用程序。我的服务器是运行Web2Py的Ubuntu服务器(我推荐=] http://web2py.com/) 我该怎么办安全的邮寄申请? 我的web2py网站提供了一个登录页面,所以如果我登录,我可以提出请求。如果我没有登录,那是不可能的。我想用cookie来验证身份。

可以使用像WebView Component这样的东西吗?

我的Http课程如下:

public class Http {

    private final static String USER = "user", PASSWORD = "passwd";

    public static String request(String requestURL,
                               List<HttpParameters> mParameters) {

    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));

        if (mParameters!=null)
            writer.write(getPostDataString(mParameters));

        writer.flush();
        writer.close();
        os.close();

        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
        }
        else {
            response="";

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}


private static String getPostDataString(List<HttpParameters> mParameters) throws UnsupportedEncodingException {

    StringBuilder mResult = new StringBuilder();
    boolean mFirst = true;

    for(HttpParameters mParameter : mParameters){
        if (mFirst)
            mFirst = false;
        else
            mResult.append("&");

        mResult.append(URLEncoder.encode(mParameter.getField(), "UTF-8"));
        mResult.append("=");
        mResult.append(URLEncoder.encode(mParameter.getValue(), "UTF-8"));
    }

    return mResult.toString();
}
}



public class HttpParameters {

private String mField, mValue;

public HttpParameters(String mField, String mValue) {
    this.mField = mField;
    this.mValue = mValue;
}

public String getField() {
    return mField;
}

public void setField(String mCode) {
    this.mField = mCode;
}

public String getValue() {
    return mValue;
}

public void setValue(String mValue) {
    this.mValue = mValue;
}
}

0 个答案:

没有答案