我需要通过 HTTPS POST 调用登录网站,然后再执行另一个 POST 调用来执行操作。
我已经用 Java 编写了一个方法来执行此任务,但现在我需要在 VB.NET 中切换我的应用程序,并且我无法使用 JVM、java 类或类似的东西。
这是我的方法:
private static void disableSslVerification() {
try{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
(避免 ssl 验证)
和
public static boolean httpsPostCall(){
disableSslVerification();
HttpsURLConnection con = null;
String query = "username="+URLEncoder.encode("user","UTF-8");
query += "&";
query += "password="+URLEncoder.encode("password","UTF-8");
String query2 = "username="+URLEncoder.encode("user","UTF-8");
query2 += "&";
query2 += "project="+URLEncoder.encode("prog","UTF-8");
query2 += "&";
query2 += "area="+URLEncoder.encode("area","UTF-8");
query2 += "&";
query2 += "system="+URLEncoder.encode("system","UTF-8");
try{
URL HTTPSurl = new URL("https://1.2.3.4/Login");
con = (HttpsURLConnection)HTTPSurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
//I use the same cookies to use the same login session
StringBuilder sb = new StringBuilder();
// find the cookies in the response header from the first request
List<String> cookies = con.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://1.2.3.4/MethodAfterLogin");
HttpsURLConnection regCon = (HttpsURLConnection)regUrl.openConnection();
regCon.setRequestProperty("Cookie", cookieHeader);
regCon.setRequestMethod("POST");
regCon.setRequestProperty("Content-length", String.valueOf(query.length()));
regCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
regCon.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
regCon.setDoOutput(true);
regCon.setDoInput(true);
DataOutputStream noutput = new DataOutputStream(regCon.getOutputStream());
noutput.writeBytes(query2);
noutput.close();
DataInputStream ninput = new DataInputStream(regCon.getInputStream());
String risp = "";
for(int c = ninput.read(); c != -1; c = ninput.read())
risp += (char)c;
ninput.close();
if(!risp.contains("New user activity created"))
return false;
else
return true;
}catch(Exception e){
e.printStackTrace();
}
}
现在我试图找到如何在 VB.NET 上执行此操作,但没有得到任何结果。我只找到了如何使用以下代码进行 POST 调用:
Dim url As New Uri("https://1.2.3.4/Login")
Dim content As HttpContent = New StringContent("{""username"":""" + login.username + """,""password"":""" + login.password + """}", System.Text.Encoding.UTF8, "application/json")
Dim returnValue As Task(Of HttpResponseMessage)
Using client As New HttpClient
client.BaseAddress = url
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Accept.Add(New Headers.MediaTypeWithQualityHeaderValue("application/json"))
returnValue = client.PostAsync(url, content)
MessageBox.Show(returnValue.Result.Content.ToString)
End Using
但是当我执行 MessageBox.Show() 方法时,他给了我“System.AggregateException”错误,并显示消息“发生一个或多个错误。”
有人可以帮我吗?
最佳答案
该错误可能是由于未处理的异常造成的。使用 try/catch block 包装您的 Web 请求代码
Try
here put web request code
Catch wex As WebException
If TypeOf wex.Response Is HttpWebResponse Then
MsgBox(DirectCast(wex.Response, HttpWebResponse).StatusCode)
End If
other web exception handling
Catch ex As Exception
other exception handling
End Try
还要记住将 Web 请求放在与 UI 线程不同的线程上,以避免阻塞
我使用此代码来制作 POST 广告,它始终有效:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 'This is for enabling SSL/TLS support
mWebClient = New WebClient()
Dim reqparm As New Specialized.NameValueCollection
reqparm.Add("username", login.username)
reqparm.Add("password", login.password)
Dim responsebytes = mWebClient.UploadValues("https://1.2.3.4/Login", "POST", reqparm) '!!! I don't know if HTTPS is supported !!!
Dim risp = System.Text.Encoding.UTF8.GetString(responsebytes)
关于java - 在单个客户端上执行两个 HTTPS POST 调用 - Java 到 Vb.Net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39228547/