How to write the following java code in vb.net?

  • Thread starter Thread starter Peter Smilenov
  • Start date Start date
P

Peter Smilenov

Guest
This is the java function:

public static String UploadFile(String name, String[] args, Boolean set_auth) throws Exception
{
//System.setProperty("https.proxyHost", "127.0.0.1");
//System.setProperty("https.proxyPort", "8888");

String charset = "UTF-8";
String boundary = "-----------------------------" + Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
String timeStamp = null;
String sMessage = "";
/* Start of Fix */
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) { }


} };
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);
/* End of the fix*/

// takes file path from first program''s argument
String filePath = args[0];
String strUrl = args[1];
File uploadFile = new File(filePath);

String userpass = kuser + ":" + kpass;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

String FileName = null;
FileWriter fw;
FileName = "log.txt";
fw = new FileWriter(dirExport + FileName,true);

try
{
timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
fw.write(timeStamp + " File to upload: " + filePath + "\r\n");
if (set_auth)
{
Authenticator.setDefault(new MyAuthenticator());
}
// creates a HTTP connection
URL url = new URL(strUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
// sets file name as a HTTP header
//httpConn.setRequestProperty("Authorization", basicAuth);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpConn.setDoOutput(true);

// opens output stream of the HTTP connection for writing data
OutputStream outputStream = httpConn.getOutputStream();

PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

writer.append("--" + boundary).append(CRLF).flush();
writer.append("Content-Dis-data; name=\"" + name + "\"; filename=\"" + filePath + "\"").append(CRLF);
writer.append("Content-Type: application/octet-stream").append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();

//Files.copy(uploadFile.toPath, outputStream);

// Opens input stream of the file for reading data
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
//System.out.println("Start writing data...");
timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
fw.write(timeStamp + " Start writing data..." + "\r\n");
//result in an out of memory error for larger files
//while ((bytesRead = inputStream.read(buffer)) != -1) {
// outputStream.write(buffer, 0, bytesRead);
//}
readFileContent(inputStream, outputStream);

writer.append(CRLF);
writer.append("--" + boundary + "--").append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
outputStream.flush(); // Important before continuing with writer!
outputStream.close();

timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
fw.write(timeStamp + " Data was written." + "\r\n");

// always check HTTP response code from server
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String response = reader.readLine();
timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
sMessage = " Server's response: " + response;

fw.write(timeStamp + sMessage + "\r\n");
} else {
timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
sMessage = " Server returned non-OK code: " + responseCode;
fw.write(timeStamp + sMessage + "\r\n");
}

}
catch(Exception ex)
{
timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
fw.write(timeStamp + " Error: " + ex.getMessage() + "\r\n");
}
finally
{
fw.close();
}
return sMessage;
}


I've wrote the following vb.net sub

Private Sub MKT532UploadFile(ByVal HttpAddress As String, ByVal Filename As String, ByRef ErrLogWriter As StreamWriter,
ByVal AuthenticationRequired As Integer, ByVal Username As String, ByVal Password As String, ByVal Name As String)
Dim charset As String = "UTF-8"
Dim boundary As String = "-----------------------------" + DateTime.Now.Ticks.ToString("x") ' Just generate some unique random value.
Dim CRLF = "\r\n" ' Line separator required by multipart/form-data.
Dim sMessage As String = ""
Dim sLine As String
Try
ErrLogWriter.WriteLine(CStr(Now) + " File To Upload: " & Filename)
'URL url = New URL(strUrl);
'HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
Dim request As HttpWebRequest = CType(WebRequest.Create(HttpAddress), HttpWebRequest)
'httpConn.setUseCaches(false);
Dim requestPolicy As New HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache)
request.CachePolicy = requestPolicy
If AuthenticationRequired = 1 Then
request.Credentials = New NetworkCredential(Username, Password)
Else
request.UseDefaultCredentials = True
request.PreAuthenticate = True
request.Credentials = CredentialCache.DefaultNetworkCredentials
End If
request.Method = "POST" 'httpConn.setRequestMethod("POST");
request.ContentType = "multipart/form-data; boundary=" + boundary 'httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
ErrLogWriter.WriteLine(CStr(Now) + "Content Type: " + request.ContentType)
Dim dataStream As Stream = request.GetRequestStream() 'OutputStream outputStream = httpConn.getOutputStream();
Dim reqWriter = New StreamWriter(dataStream, Encoding.UTF8) 'PrintWriter writer = New PrintWriter(New OutputStreamWriter(outputStream, charset), True);
reqWriter.AutoFlush = True
sLine = "--" + boundary + CRLF
ErrLogWriter.WriteLine(CStr(Now) + sLine)
reqWriter.Write(sLine) 'writer.append("--" + boundary).append(CRLF).flush();
sLine = "Content-Dis-data; name=\" + Name + "\; filename=\" + Filename + "\" + CRLF
ErrLogWriter.WriteLine(CStr(Now) + sLine)
reqWriter.Write(sLine) 'writer.append("Content-Dis-data; name=\"" + name + " \ "; filename=\"" + filePath + " \ "").append(CRLF);
sLine = "Content-Type: application/octet-stream" + CRLF
ErrLogWriter.WriteLine(CStr(Now) + sLine)
reqWriter.Write(sLine) 'writer.append("Content-Type: application/octet-stream").append(CRLF); // Text file itself must be saved In this charset!
sLine = CRLF
ErrLogWriter.WriteLine(CStr(Now) + CRLF)
reqWriter.Write(sLine)
reqWriter.Flush()
Dim rdr = New FileStream(Filename, FileMode.Open) 'FileInputStream inputStream = New FileInputStream(uploadFile);
Dim reader = New StreamReader(rdr)
ErrLogWriter.WriteLine(CStr(Now) + " Start Writting Data ... ")
Using reader
While Not reader.EndOfStream
sLine = reader.ReadLine()
reqWriter.Write(sLine)
End While
End Using
reader.Close()
sLine = CRLF
ErrLogWriter.WriteLine(CStr(Now) + sLine)
reqWriter.Write(sLine) 'writer.append(CRLF);
sLine = "--" + boundary + "--" + CRLF
ErrLogWriter.WriteLine(CStr(Now) + sLine)
reqWriter.Write(sLine) 'writer.append("--" + boundary + "--").append(CRLF).flush(); // CRLF Is important! It indicates End Of boundary
reqWriter.Flush()
dataStream.Flush() 'outputStream.flush(); // Important before continuing With writer!
dataStream.Close() 'outputStream.close();
ErrLogWriter.WriteLine(CStr(Now) + " Data was written.") 'fw.write(timeStamp + " Data was written." + "\r\n");
Dim response As WebResponse = request.GetResponse()
' Display the status.
ErrLogWriter.WriteLine(CStr(Now) + " Response status: " & CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
reader = New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Display the content.
ErrLogWriter.WriteLine(CStr(Now) + " Response from server: " & responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
Catch
ErrLogWriter.WriteLine(CStr(Now) + " Error: " & Err.Description)
Finally
ErrLogWriter.WriteLine(CStr(Now) + " Completed")
End Try

End Sub



But it seems that something is wrong because the response from the server is : "Error: you must upload the file."

Continue reading...
 
Back
Top