gpt4 book ai didi

java - https Session 和 posting 问题

转载 作者:太空狗 更新时间:2023-10-29 15:39:44 25 4
gpt4 key购买 nike

我有一个应用程序需要能够通过身份验证请求和注册请求发布到 https。目前我可以将我的身份验证请求发布到 https,并且工作正常。当我尝试将我的注册请求发布到 https 时,我不断收到服务器响应,说我需要进行身份验证。我在尝试注册之前进行身份验证。

服务器管理员说我可能不会保留 session 。我刚开始使用 android 和 java 做事。我是这个 https 的新手。我想知道是否有人可以帮助我,我不知道这是否是问题所在,甚至不知道如何在 android 中保留 https session 。

下面是我的代码,非常感谢任何建议!!!!提前致谢!!

//my helper class
public class SmartDBHelper {

private static Context tThis;
private static SmartDBHelper sDBHObject;
private static String macAddress;
private static String ipAddress;
private static HttpsURLConnection https;

/* constructor, private prevents any other class from instantiating */
private SmartDBHelper() {

}

public static synchronized SmartDBHelper getSDBHObject() {
if(sDBHObject == null) {
sDBHObject = new SmartDBHelper();
}
return sDBHObject;
}

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

public static synchronized void setSmartContext(SmartApp smartApp) {
tThis = (Context) smartApp;
}

private static synchronized void setMACIPAddress() {
WifiManager wifiMan = (WifiManager) tThis.getSystemService (tThis.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
macAddress = wifiInf.getMacAddress().replace(':', '-');
ipAddress = wifiMan.getDhcpInfo().toString();
int startIndex = ipAddress.indexOf(' ');
int endIndex = ipAddress.indexOf(' ', startIndex + 1);
ipAddress = ipAddress.substring(startIndex + 1, endIndex);
}

/* this function is to authenticate with the database
* it returns the id_subject, if it is greater than 0
* authentication was successful.
*/
public static synchronized int authenticate() throws MalformedURLException, ProtocolException, IOException {
Map<String, String> tempMap = new LinkedHashMap<String, String>();
tempMap.put((String) tThis.getResources().getText(R.string.postAction), (String) tThis.getResources().getText(R.string.postAuthenticate));
tempMap.put((String) tThis.getResources().getText(R.string.authUName), "username");
tempMap.put((String) tThis.getResources().getText(R.string.authPWord), "password");
String tempUrl = "https://ipaddress/health_monitoring/admin.php";
return Integer.parseInt(post(tempUrl, tempMap));
}

/* this function is to register the server to the database
* not sure of return value
*/
public static synchronized int registerServer(String nameOfServer, String description) throws MalformedURLException, ProtocolException, IOException {
setMACIPAddress();
Map<String, String> tempMap = new LinkedHashMap<String, String>();
tempMap.put((String) tThis.getResources().getText(R.string.postAction), (String) tThis.getResources().getText(R.string.postAddServer));
tempMap.put((String) tThis.getResources().getText(R.string.addServerName), "Phone");
tempMap.put((String) tThis.getResources().getText(R.string.addServerDescription), "Android");
tempMap.put((String) tThis.getResources().getText(R.string.addServerURL), "");
tempMap.put((String) tThis.getResources().getText(R.string.addServerIPAddress), ipAddress);
tempMap.put((String) tThis.getResources().getText(R.string.addServerMAC), macAddress);

String tempUrl = "https://ipaddress/health_monitoring/admin.php";
return Integer.parseInt(post(tempUrl, tempMap));
}

// always verify the host - dont check for certificate
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};

/**
* Trust every server - dont check for any certificate
*/
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}

public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };

// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}

private static String post(String urlString, Map formParameters)
throws MalformedURLException, ProtocolException, IOException {
DataOutputStream ostream = null;

trustAllHosts();
URL tempUrl;
StringBuffer buf = new StringBuffer();
if(formParameters != null) {
Set parameters = formParameters.keySet();
Iterator it = parameters.iterator();

for(int i = 0, paramCount = 0; it.hasNext(); i++) {
String parameterName = (String) it.next();
String parameterValue = (String) formParameters.get(parameterName);

if(parameterValue != null) {
parameterValue = URLEncoder.encode(parameterValue);
if(paramCount > 0) {
buf.append("&");
}
buf.append(parameterName);
buf.append("=");
buf.append(parameterValue);
++paramCount;
}
}
}
urlString = urlString + "?" + buf;
Log.v("smartdbhelper url string", urlString);
tempUrl = new URL(urlString);
https = (HttpsURLConnection) tempUrl.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
Log.v("smartdbhelper adding post parameters", https.toString());
https.setRequestMethod("POST");
https.setDoInput(true);
https.setDoOutput(true);
ostream = new DataOutputStream(https.getOutputStream());
ostream.writeBytes(buf.toString());

if( ostream != null ) {
ostream.flush();
ostream.close();
}
Object contents = https.getContent();
InputStream is = (InputStream) contents;
StringBuffer buf2 = new StringBuffer();
int c;
while((c = is.read()) != -1) {
buf2.append((char)c);
Log.v("smartdbhelper bugger", buf2.toString());
}
//https.disconnect();
return buf2.toString();
}
}

最佳答案

听起来您可能需要处理 cookie header 以保留 session 。如果是这种情况,则这不是 HTTPS 特有的。发出第一个请求时,您需要找到 Set-Cookie 响应 header 。然后,之后的每个请求都将通过 Cookie 请求 header 传递。这是您可以根据自己的情况进行调整的基本示例:

// your first request that does the authentication
URL authUrl = new URL("https://example.com/authentication");
HttpsURLConnection authCon = (HttpsURLConnection) authUrl.openConnection();
authCon.connect();

// temporary to build request cookie header
StringBuilder sb = new StringBuilder();

// find the cookies in the response header from the first request
List<String> cookies = authCon.getHeaderFields().get("Set-Cookie");
if (cookies != null) {
for (String cookie : cookies) {
if (sb.length() > 0) {
sb.append("; ");
}

// only want the first part of the cookie header that has the value
String value = cookie.split(";")[0];
sb.append(value);
}
}

// build request cookie header to send on all subsequent requests
String cookieHeader = sb.toString();

// with the cookie header your session should be preserved
URL regUrl = new URL("https://example.com/register");
HttpsURLConnection regCon = (HttpsURLConnection) regUrl.openConnection();
regCon.setRequestProperty("Cookie", cookieHeader);
regCon.connect();

关于java - https Session 和 posting 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5609269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com