在单个客户端上执行两个HTTPS POST调用 - Java到Vb.Net

时间:2016-08-30 13:14:56

标签: java vb.net post https

我需要使用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()方法时,他给了我&#34; System.AggregateException&#34;错误消息&#34;发生了一个或多个错误。&#34;

有人可以帮我一把吗?

1 个答案:

答案 0 :(得分:0)

错误可能是由于未处理的异常造成的。使用try / catch块包装您的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不同的线程上,以避免阻止它

我使用此代码制作广告时始终有效的广告:

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)