I want to convert this VB.NET code to use in an Android Studio Project (JAVA)
Imports System.Text
Imports System.Security.Cryptography
Public Class Form1
Public Function md5hash(ByVal txt As String)
Dim md5 As MD5 = New MD5CryptoServiceProvider
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(txt))
Dim reslt As Byte() = md5.Hash
Dim strbuilder As New StringBuilder
For i As Integer = 0 To reslt.Length - 1
strbuilder.Append(reslt(i).ToString("x2"))
Next
Dim ss As String = strbuilder.ToString
Dim newss As String = ss.Substring(0, 4) + "-" + ss.Substring(4, 4) + "-" + ss.Substring(8, 4) + "-" + ss.Substring(12, 4) + "-" + ss.Substring(16, 4)
Return newss.ToUpper
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
TxtKey.Text = md5hash(TxtID.Text)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
How can I do this? To convert VB.NET Visual Basic 2010 script into android studio java
Related
I have a string than I want to encrypt to send it over an insecure channel.
I want to:
Convert to int my-val & my-private-key. Then, multiply both. Send it. When receiving it, divide by my-private-key converted as int and get my-val.
I tried to used Integer.parseInt and Integer.toString as suggested here. It seems to work with System.out.println(Integer.parseInt("Kona", 27)); (as Java's documentation said)
So I made this:
int base = 27;
String key = "some key";
String cmd = "some val";
int based = Integer.parseInt(cmd, base);
System.out.println("Based: " + based);
int crypted = based * Integer.parseInt(key, base);
System.out.println("Crypted: " + crypted);
// here use un-secure channel to send/receive
int received = crypted;
int back = received / Integer.parseInt(key, base);
System.out.println("Get back: " + back);
System.out.println("Final result: " + Integer.toString(back, base));
But I get Exception in thread "main" java.lang.NumberFormatException: For input string: "some val" at the 4st line.
I tried with base 10, 16, 27, 32. Even if I understand why 10 & 16 doesn't work, why 27 & 32 don't ? How can I fix it ?
Based on below wikipedia link of numeral system, Java will check each character of your input string against the range of radix parameter and if its not in range than it will throw exception.
Visit https://en.wikipedia.org/wiki/List_of_numeral_systems,
Apart from that, Below is explanation from geeksforgeek site.
The string is null or of zero-length
The value represented by the string is not a value of type int
Specifically for the parseInt(String s, int radix) variant of the function:
The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX
*
Each character of input string has min and max radix parameter.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1
Custom logic for conversion
String name = "some val";
long key = 0;
for (int i = 0;i<name.length();i++)
key+= (name.charAt(i) - 'a'+1 ) * Math.pow(26,name.length() - i - 1 );
System.out.println(key);
Above code is taken Converting name to a key using radix-26
I was looking to encrypt with another string. I get the idea to multiply both, and so convert them into int. But, it seems to have informations lost with operation.
So, I searched for another way, and I found this one:
private static final String ALGORITHM = "AES";
private static final Key MY_KEY = new SecretKeySpec("16-char priv key".getBytes(), ALGORITHM);
private Cipher getCipher(int mode) throws Exception {
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(mode, MY_KEY);
return c;
}
public String encrypt(String valueToEnc) throws Exception {
return Base64.getEncoder().encodeToString(getCipher(Cipher.ENCRYPT_MODE).doFinal(valueToEnc.getBytes()));
}
public String decrypt(String encryptedValue) throws Exception {
return new String(getCipher(Cipher.DECRYPT_MODE).doFinal(Base64.getDecoder().decode(encryptedValue)));
}
How it works ? It encrypt and decrypt with a key. This key should be a 16-chars one. Also, to make it easier to show/send/receive, it's converted into base 64.
Example of how to use:
String myVal = "some val";
String encrypt = encrypt(myVal);
System.out.println("Encrypt: " + encrypt);
String decrypt = decrypt(encrypt);
System.out.println("Decrypt: " + decrypt);
Output:
Encrypt: ERJZ7ZOJcNpQEAvrb6wPOA==
Decrypt: some val
I used SCALE Codec for java offline address generation. but I see that generated address and polkadot.js generated address are not alike.
I use bitcoinj 's MnemonicCode generation mnemonic, and I toseed the mnemonic get seed;
this is my code;
public void createAddress() throws Exception {
System.out.println("Generate a new Root Key + derive a `demo` address from that key");
int number = 0;
byte[] initialEntropy = new byte[128 / 8];
SecureRandomUtils.secureRandom().nextBytes(initialEntropy);
String mnemonic = "devote fatigue dice clock lock cross creek neutral minute achieve betray curve";
String[] mm = mnemonic.split(" ");
List<String> strings = Arrays.asList(mm.clone());
System.out.println(mnemonic);
String n = Utils.SPACE_JOINER.join(strings);
System.out.println(n);
byte[] seed = toSeed(strings, "");
String s = Hex.encodeHexString(seed);
System.out.println(s);
Schnorrkel instance = Schnorrkel.getInstance();
Schnorrkel.KeyPair rootKey = instance.generateKeyPairFromSeed(seed);
System.out.println(" Root Key: " + Hex.encodeHexString(rootKey.getSecretKey()));
Schnorrkel.KeyPair key = instance.deriveKeyPair(rootKey, Schnorrkel.ChainCode.from("".getBytes()));
Address address = new Address(SS58Type.Network.LIVE, key.getPublicKey());
System.out.println(" Address: " + address);
System.out.println("Public Key: " + Hex.encodeHexString(key.getPublicKey()));
System.out.println("Secret Key: " + Hex.encodeHexString(key.getSecretKey()));
}
public static byte[] toSeed(List<String> words, String passphrase) {
checkNotNull(passphrase, "A null passphrase is not allowed.");
// To create binary seed from mnemonic, we use PBKDF2 function
// with mnemonic sentence (in UTF-8) used as a password and
// string "mnemonic" + passphrase (again in UTF-8) used as a
// salt. Iteration count is set to 4096 and HMAC-SHA512 is
// used as a pseudo-random function. Desired length of the
// derived key is 512 bits (= 64 bytes).
//
String pass = Utils.SPACE_JOINER.join(words);
String salt = "mnemonic" + passphrase;
final Stopwatch watch = Stopwatch.createStarted();
byte[] seed = PBKDF2SHA512.derive(pass, salt, 2048, 32);
watch.stop();
System.out.println("PBKDF2 took {}" + watch);
return seed;
}
polkadot.js generated address is "12EgmkT6NHjTjtwcvfBFu1dkPEN9TLFo3ftA4L2ZcmkCfQCp";
i use my code generated address is "12YTJRjPRsw34wBp2Ewfr9oBP9w47RpKKw4CPZF2zaCga1Hk"
how do I generate similar polkadot.js' address ?
This is my request code. aa means my consumer key and bb is userAcessTokenSecret. I changed the values for the sake of security. I don't know is it becasue of cursor parameter or the ways of encoding and hashing the values and keys.
public static void getLocationAndNameOfFollowers(String userAcessToken, String userAcessTokenSecret) throws IOException, InvalidKeyException, NoSuchAlgorithmException {
userAcessTokenSecret = "bb";
String signingKey = GenerateSignature.oAuthSigningKey("aa", userAcessTokenSecret);
long ts = new Timestamp(System.currentTimeMillis()).getTime() / 1000;
String timeStamp = String.valueOf(ts);
String nonce = GenerateSignature.generateNonce("aa", timeStamp);
String baseString = GenerateSignature.oAuthBaseString("GET", "https://api.twitter.com/1.1/followers/list.json?",
"cursor-1", "fHkdJVy3x1fKE1Yop9qraJyCp", userAcessToken, timeStamp, nonce);
String oauth_signature = GenerateSignature.oAuthSignature(baseString, signingKey);
JSONObject response = Unirest.get("https://api.twitter.com/1.1/followers/list.json?cursor=-1")
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "OAuth oauth_consumer_key=\"consumer_key\"," +
"oauth_token=" + "\"" + userAcessToken +"\""+ "," +
"oauth_signature_method=" + "\"HMAC-SHA1\"," +
"oauth_timestamp=" + "\""+timeStamp + "\"" + "," +
"oauth_nonce=" + "\""+nonce + "\"" + "," +
"oauth_version=\"1.0\"," +
"oauth_signature=" + "\"" +oauth_signature + "\"")
.asJson().getBody().getObject();
The code in below contains my helper functions.
private static String percentEncoding(String originalString) {
String encodedString = Base64.getUrlEncoder().encodeToString(originalString.getBytes());
return encodedString;
}
public static String oAuthBaseString(String method, String url, String parameters, String key, String token, String timestamp, String nonce) {
System.out.println("generated sorted parameter string -> "+generateSortedParameterString(parameters, key, token, timeStamp , nonce));
String res = method + "&" + percentEncoding(url)
+ "&" + generateSortedParameterString(parameters, key, token, timeStamp , nonce);
System.out.println("oauth base string -> \n\n\n" + res);
return res;
}
public static String oAuthSignature(String baseString, String tokenSecret) throws NoSuchAlgorithmException, InvalidKeyException {
byte[] bytes = baseString.getBytes(StandardCharsets.UTF_8);
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(bytes, "HmacSHA1"));
byte[] res = mac.doFinal(tokenSecret.getBytes(StandardCharsets.UTF_8));
return percentEncoding(Base64.getEncoder().toString());
}
public static String oAuthSigningKey(String consumerSecret, String accessTokenSecret) {
return consumerSecret + "&" + accessTokenSecret;
}
public static String generateNonce(String consumerKey, String timeStamp) {
String nonce = Base64.getEncoder().encodeToString((consumerKey + ":" + timeStamp).getBytes());
return nonce;
}
public static String generateSortedParameterString(String parameter, String key, String token, String timeStamp, String nonce) {
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("oauth_consumer_key", key);
parameters.put("oauth_nonce", nonce);
parameters.put("oauth_signature_method", "HMAC-SHA1");
parameters.put("oauth_timestamp", timeStamp);
parameters.put("oauth_token", token);
parameters.put("oauth_version", "1.0");
System.out.println("parameter map is here -> "+parameters);
String parameterString = parameters.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> percentEncoding(e.getKey()) + "=" + percentEncoding(e.getValue()))
.collect(Collectors.joining("&"));
return parameterString;
}
I am getting this response
{"errors":[{"code":32,"message":"Could not authenticate you."}]}
I see your code and looks like you may not have finished the steps needed before you make a call to get followers.
Since Twitter follows OAuth1 here is what you need to do for this. If you confirm that you have done these then I can help you with the signing process.
The variables that you are working with
consumerKey = Copied from twitter during registration
accesstokenSecret = Copied from twitter during registration
oauth_token = Received as response from step 1 below
oauth_token_secret = Received as response from step 2 below
oauth_verifier = Received as response from step 3 below
accesstoken = Received as response from step 4 below. Finally to be used while signing all API calls
Steps for OAuth 1.0 that twitter follows
GET oauth_token making signed call to https://api.twitter.com/oauth/request_token. Twitter will return oauth_token and oauth_token_secret
Redirect user to https://api.twitter.com/oauth/authorize?oauth_token={{oauth_token}}
User Authenticates and twitter will send a code to your redirect url
Then send a signed request to https://api.twitter.com/oauth/access_token to recieve the access_token
The process for signing are the same for each step with changes to the baseString and signing key. If you have achieved the signing logic for step1. All the others should work.
If you have not done the above steps and are struggling with signing at step1 then I'll help you with the basic structure of signing. Do confirm?
I work at Pathfix and we built it out as a middleware to solve the exact problem without having you to download SDK. If you are dealing with multiple Providers, you will eventually notice the lack of reusability and bulk of unneccessary code. It might save you hours and $$. All of what you are trying to achieve can take you not more than 10 minutes :)
I'm writing an application to launch Minecraft with mods, and will also keep the mods up-to-date. I'm getting a JVM error that I can't seem to fix.
I've been searching on Stack Exchange and Stack Overflow for answers and can't find anything useful on Google. I'm actually basing my code off of another question I found on this site, but it was missing a lot of important information.
What is this error caused by? Is it a problem with my code? Is there any way to fix it?
EDIT: Is it possible to get the output of the JVM? I need more information for debugging.
Here is my VB.NET code.
Imports System.Net
Imports System.IO
Imports System.Threading
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class Form1
Dim streamReader As StreamReader
Dim Root As String = "C:\Users\admin\AppData\Roaming\.minecraft"
Dim SelectedGameVersion As String = "1.10"
Dim MinecraftJavaPath = "C:\Program Files (x86)\Minecraft\runtime\jre-x64\1.8.0_25\bin\javaw.exe"
Dim JavaPath = "C:\Program Files\Java\jre1.8.0_121\bin\javaw.exe"
Dim FileList As New ArrayList
Dim assets As String = "C:\Users\admin\AppData\Roaming\.minecraft\assets\index\1.10.json"
Dim MinMemAlloc As String = "1G"
Dim MaxMemAlloc As String = "4G"
Dim mainClass As String = "net.minecraft.client.main.Main"
Dim accessToken As String = "INVALID"
Dim id As String = "INVALID"
Dim username As String = "INVALID"
Dim legacy As Boolean = False
Dim debugString As String = ""
Dim LIBRARIES As String = Root + "\versions\1.10.2\1.10.2-natives"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
'debugString = "UUID: " + id + ", Username: " + username + ", Legacy?: " + legacy.ToString
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\java3d\vecmath\1.5.2\vecmath-1.5.2.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\net\sf\trove4j\trove4j\3.0.3\trove4j-3.0.3.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\ibm\icu\icu4j-core-mojang\51.2\icu4j-core-mojang-51.2.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\net\sf\jopt-simple\jopt-simple\4.6\jopt-simple-4.6.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\paulscode\codecwav\20101023\codecwav-20101023.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\paulscode\librarylwjglopenal\20100824\librarylwjglopenal-20100824.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\io\netty\netty-all\4.0.23.Final\netty-all-4.0.23.Final.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\google\guava\guava\17.0\guava-17.0.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\commons-io\commons-io\2.4\commons-io-2.4.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\google\code\gson\gson\2.2.4\gson-2.2.4.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\mojang\authlib\1.5.24\authlib-1.5.24.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\com\mojang\realms\1.10.6\realms-1.10.6.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-api\2.0-beta9\log4j-api-2.0-beta9.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.0-beta9\log4j-core-2.0-beta9.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl\lwjgl\2.9.4-nightly-20150209\lwjgl-2.9.4-nightly-20150209.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl\lwjgl_util\2.9.4-nightly-20150209\lwjgl_util-2.9.4-nightly-20150209.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl\lwjgl-platform\2.9.4-nightly-20150209\lwjgl-platform-2.9.4-nightly-20150209-natives-windows.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\net\java\jinput\jinput-platform\2.0.5\jinput-platform-2.0.5-natives-windows.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\tv\twitch\twitch\6.5\twitch-6.5.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\tv\twitch\twitch-platform\6.5\twitch-platform-6.5-natives-windows-64.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\libraries\tv\twitch\twitch-external-platform\4.5\twitch-external-platform-4.5-natives-windows-64.jar;") ' UPDATED
FileList.Add("C:\Users\admin\AppData\Roaming\.minecraft\versions\" + SelectedGameVersion + ".jar;") ' UPDATED
Catch ex As Exception
MsgBox(ex.Message, , "Oh noes!")
End Try
End Sub
Public Sub authRequest()
Try
Dim status As HttpStatusCode = HttpStatusCode.ExpectationFailed
Dim response As Byte() = PostResponse("http://authserver.mojang.com/authenticate", "{""agent"": {""name"": ""Minecraft"",""version"": 1},""username"": " + txtUsername.Text + ",""password"": " + txtPassword.Text + "}", status)
Dim responseString As String
responseString = System.Text.Encoding.UTF8.GetString(response)
responseString = "NULL"
Console.WriteLine("Response Code: " & status)
Console.WriteLine("Response String: " & responseString)
Dim json As String = responseString
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "availableProfiles"
For Each profileVar As JObject In item.Values
id = profileVar("id")
username = profileVar("name")
legacy = profileVar("legacy")
Next
Case ""
For Each profileVar As Object In item.Values
accessToken = profileVar("accessToken")
'MsgBox(profileVar("accessToken"), , "Debug")
Next
End Select
Next
Catch ex As Exception
MsgBox(ex.Message, , "Oh noes!")
End Try
End Sub
Public Sub launchGame()
Try
If Not File.Exists(Root + "\versions\" + SelectedGameVersion + "\" + SelectedGameVersion + ".jar") Then
MsgBox("File not found: " + SelectedGameVersion + ".jar")
Else
Dim Gamelibraries As String = Nothing
For i = 0 To FileList.Count - 1
Gamelibraries += FileList.Item(i) +
Environment.NewLine()
Next
Dim p As New Process()
p.StartInfo.FileName = JavaPath
p.StartInfo.Arguments = " -Xms" + MinMemAlloc + "M -Xmx" + MaxMemAlloc + "M " +
"-Djava.library.path=" + LIBRARIES + "-natives -cp " +
Gamelibraries.ToString() + mainClass +
" --username=" + username +
" --version " + SelectedGameVersion +
" --gameDir " + Root +
" --assetsDir " + Root + "\assets" +
" --assetIndex 1.10" +
" --accessToken " + accessToken +
" --userProperties {}" +
" --userType mojang" +
" --uuid " + id +
" --nativeLauncherVersion 307"
p.StartInfo.WorkingDirectory = Root
p.StartInfo.CreateNoWindow = False
p.StartInfo.UseShellExecute = False
p.EnableRaisingEvents = True
Application.DoEvents()
p.StartInfo.RedirectStandardError = True
p.StartInfo.RedirectStandardOutput = True
'AddHandler p.ErrorDataReceived, AddressOf p_OutputDataReceived
'AddHandler p.OutputDataReceived, AddressOf p.OutputDataReceived
p.Start()
p.BeginErrorReadLine()
p.BeginOutputReadLine()
'Button1.Text = "Play"
'Button1.Enabled = True
'Button2.Enabled = True
'Button3.Enabled = True
'Button4.Enabled = True
'Button5.Enabled = True
End If
Catch ex As Exception
MsgBox(ex.Message, , "Oh noes!")
End Try
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Try
authRequest()
'Thread.Sleep(3000)
'MsgBox(debugString, , "Debug")
launchGame()
Catch ex As Exception
MsgBox(ex.Message, , "Oh noes!")
End Try
End Sub
Public Function PostResponse(url As String, content As String, ByRef statusCode As HttpStatusCode) As Byte()
Dim responseFromServer As Byte() = Nothing
Dim dataStream As Stream = Nothing
Try
Dim request As WebRequest = WebRequest.Create(url)
request.Timeout = 120000
request.Method = "POST"
Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(content)
request.ContentType = "application/json"
request.ContentLength = byteArray.Length
dataStream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim ms As New MemoryStream()
Dim thisRead As Integer = 0
Dim buff As Byte() = New Byte(1023) {}
Do
thisRead = dataStream.Read(buff, 0, buff.Length)
If thisRead = 0 Then
Exit Do
End If
ms.Write(buff, 0, thisRead)
Loop While True
responseFromServer = ms.ToArray()
dataStream.Close()
response.Close()
statusCode = HttpStatusCode.OK
Catch ex As WebException
If ex.Response IsNot Nothing Then
dataStream = ex.Response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim resp As String = reader.ReadToEnd()
statusCode = DirectCast(ex.Response, HttpWebResponse).StatusCode
Else
Dim resp As String = ""
statusCode = HttpStatusCode.ExpectationFailed
End If
Catch ex As Exception
statusCode = HttpStatusCode.ExpectationFailed
End Try
Return responseFromServer
End Function
End Class
NOTE: I'm very new to JSON, so if you could point out if there's something wrong with it that would help me with my project a lot.
Public Overridable Sub printMatrix()
administrator.ListBox1.Items.Add(ControlChars.Lf)
For i As Integer = 1 To matrix.Length - 1
For j As Integer = 1 To matrix.Length - 1
Dim parser() As String = matrix(i)(j).Split(New Char() {" "c})
' Dim parser() As String = matrix(i)(j).Split(" ", True)
For k As Integer = 0 To parser.Length - 1
If Regex.IsMatch(parser(k), "[a-zA-Z ]*\d+.*") Then
Console.Write(Double.Parse(parser(k)) & " ")
End If
'If parser(k).matches("[a-zA-Z ]*\d+.*") Then
' Console.Write(Double.Parse(parser(k)) & " ")
'End If
Next k
administrator.ListBox1.Items.Add("|" & ControlChars.Tab)
Next j
administrator.ListBox1.Items.Add(ControlChars.Lf)
Next i
End Sub
Getting a NullReferenceException on Split String error when running program.
Sorry, new here. I'm parsing through an array and trying to print the values to a listbox. The original code was written in Java and after using a converter to add it to my vb.net code I'm getting this null exception.
Error Message
Try this:
Dim parser As new String() = matrix(i)(j).Split(New Char() {" "c})