編輯:我現在的工作,其實我是不正確的取令牌,我需要從loginsite本身,而不是在Set-Cookie頭的價值得到它。結果服務器收到不正確的數據並給出了500個響應碼。 我張貼的如果有人跑進了同樣的問題工作代碼。
我把這全部包裝在一個HttpUtility類使用一個靜態HttpsURLConnection。
/**
* Represents an HTTP connection
*/
private static HttpsURLConnection httpConn;
從Loginsite獲取令牌:
private String getToken() {
String result = "";
try {
Document doc = Jsoup.connect("https://mobiel.host.nl/login").get();
Element inputElements = doc.getElementsByTag("input").first();
result = inputElements.attr("value");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
處理餅乾:
final public void saveCookies(HttpURLConnection connection, Context context) {
CookieHandler.setDefault(myCookies);
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = null;
try {
cookiesHeader = headerFields.get("Set-Cookie");
} catch (Exception e) {
e.printStackTrace();
}
if (cookiesHeader != null && myCookies != null) {
for (String cookie : cookiesHeader) {
try {
cookie = cookie.replace("\"", "");
myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
new_cookie = TextUtils.join(";", myCookies.getCookieStore().getCookies());
PreferenceManager.getDefaultSharedPreferences(LoginActivity.myContext).edit().putString("cookie", new_cookie).commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
final public void loadCookies(HttpURLConnection connection, Context context) {
if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
Log.w("NewCookies: ", myCookies.getCookieStore().getCookies().toString());
} else {
new_cookie = PreferenceManager.getDefaultSharedPreferences(LoginActivity.myContext).getString("cookie" , "");
connection.setRequestProperty("Cookie", new_cookie);
}
}
禁用SSL證書檢查,使用這僅用於測試目的:
private static void disableSSLCertificateChecking() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// Not implemented
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// Not implemented
}
} };
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
GET請求:
POST請求:
public HttpsURLConnection sendPostRequest(String requestURL, Context context) throws IOException {
int TIMEOUT_VALUE = 10000;
token = getToken(); // Get token from Loginsite
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("__RequestVerificationToken", token)
.appendQueryParameter("ReturnUrl", "")
.appendQueryParameter("Username", user)
.appendQueryParameter("Password", pass);
String query = builder.build().getEncodedQuery();
try {
boolean redirect = false;
URL url = new URL(requestURL);
HttpsURLConnection httpConn = null;
httpConn = (HttpsURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setUseCaches(false);
httpConn.setReadTimeout(TIMEOUT_VALUE);
httpConn.setConnectTimeout(TIMEOUT_VALUE);
httpConn.setInstanceFollowRedirects(false);
System.out.println("Request URL ... " + url);
httpConn.setRequestProperty("User-Agent", USER_AGENT);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Length", Integer.toString(query.length()));
// sends POST data
OutputStream os = httpConn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
// Handle servererror code
int status = httpConn.getResponseCode();
if (status > 400) {
InputStream errorstream = httpConn.getErrorStream();
BufferedReader br = null;
if (errorstream == null) {
InputStream inputstream = httpConn.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
} else {
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String message;
while ((nachricht = br.readLine()) != null) {
response += message;
}
}
// Handle redirects, normally, 3xx is redirect
if (status != HttpsURLConnection.HTTP_OK) {
if (status == HttpsURLConnection.HTTP_MOVED_TEMP
|| status == HttpsURLConnection.HTTP_MOVED_PERM
|| status == HttpsURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
if (redirect) {
// get redirect url from "location" header field
String newUrl = httpConn.getHeaderField("Location");
// Get the cookie if needed, for login
saveCookies(httpConn, context);
// Open the new connnection again
httpConn = (HttpsURLConnection) url.openConnection();
loadCookies(httpConn, context); //Include the cookies
httpConn.setRequestProperty("User-Agent", USER_AGENT);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Log.w("Redirected to URL : ", newUrl);
}
} catch (SocketTimeoutException e) {
Log.e("More than ", TIMEOUT_VALUE + " elapsed.");
}
// Check if correctly logged in
httpConn.getHeaderFields().toString();
List<HttpCookie> cookies = myCookies.getCookieStore().getCookies();
for (HttpCookie cookie : cookies) {
if (cookie.getName().equals(".ASPXAUTH")) {
Log.e(".ASPXAUTH-Session: ", "Logged in!");
}
}
saveCookies(httpConn, context); // Save Set-Cookies for next session
return httpConn;
}
'500響應碼'。這意味着? – greenapps
@greenapps,500表示:服務器遇到意外情況,無法完成請求。 我的代碼不正確?我承認是的。 – Simon
你必須檢查服務器日誌,看看有什麼問題。 –