我正在尝试触发http发布请求,而我的问题是我在DataOutputStream
处收到异常,我想我知道哪里,但我不知道为什么。
该代码是
public string sendFileToServer(string filename, string targetUrl)
{
string response = "error";
Log.Error("Image filename", filename);
Log.Info("url", targetUrl);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
string pathToOurFile = filename;
string urlServer = targetUrl;
string lineEnd = "\r\n";
string twoHyphens = "--";
string boundary = "*****";
Java.Text.DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection)url.OpenConnection();
// Allow Inputs & Outputs
connection.DoInput = true;
connection.DoOutput = true;
connection.UseCaches = false;
connection.SetChunkedStreamingMode(1024);
// Enable POST method
connection.RequestMethod = "POST";
connection.SetRequestProperty("Connection", "Keep-Alive");
connection.SetRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.OutputStream);
outputStream.WriteBytes(twoHyphens + boundary + lineEnd);
string connstr = null;
connstr = "Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd;
Log.Info("Connstr", connstr);
outputStream.WriteBytes(connstr);
outputStream.WriteBytes(lineEnd);
bytesAvailable = fileInputStream.Available();
bufferSize = Java.Lang.Math.Min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.Read(buffer, 0, bufferSize);
Log.Error("Image length", bytesAvailable + "");
try
{
while (bytesRead > 0)
{
try
{
outputStream.Write(buffer, 0, bufferSize);
}
catch (OutOfMemoryError e)
{
e.PrintStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.Available();
bufferSize = Java.Lang.Math.Min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.Read(buffer, 0, bufferSize);
}
}
catch (Java.Lang.Exception e)
{
e.PrintStackTrace();
response = "error";
return response;
}
outputStream.WriteBytes(lineEnd);
outputStream.WriteBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = (int)connection.ResponseCode;
string serverResponseMessage = connection.ResponseMessage;
Log.Info("Server Response Code ", "" + serverResponseCode);
Log.Info("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200)
{
response = "true";
}
string CDate = null;
Date serverTime = new Date(connection.Date);
try
{
CDate = df.Format(serverTime);
}
catch (Java.Lang.Exception e)
{
e.PrintStackTrace();
Log.Error("Date Exception", e.Message + " Parse Exception");
}
Log.Info("Server Response Time", CDate + "");
filename = CDate
+ filename.Substring(filename.LastIndexOf("."),
filename.Length);
Log.Info("File Name in Server : ", filename);
fileInputStream.Close();
outputStream.Flush();
outputStream.Close();
outputStream = null;
}
catch (Java.Lang.Exception ex)
{
// Exception handling
response = "error";
Log.Error("Send file Exception", ex.Message + "");
ex.PrintStackTrace();
}
return response;
}
这是在例外情况下打印的完整堆栈跟踪:
05-29 01:49:10.059 W/System.err(22768): android.os.NetworkOnMainThreadException
05-29 01:49:10.450 W/System.err(22768): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1108)
05-29 01:49:10.450 W/System.err(22768): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-29 01:49:10.450 W/System.err(22768): at libcore.io.IoBridge.connectErrno(IoBridge.java:133)
05-29 01:49:10.450 W/System.err(22768): at libcore.io.IoBridge.connect(IoBridge.java:118)
05-29 01:49:10.450 W/System.err(22768): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-29 01:49:10.450 W/System.err(22768): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-29 01:49:10.450 W/System.err(22768): at java.net.Socket.connect(Socket.java:849)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:77)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
05-29 01:49:10.450 W/System.err(22768): at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
05-29 01:49:10.450 W/System.err(22768): at mono.android.view.View_OnClickListenerImplementor.n_onClick(Native Method)
05-29 01:49:10.450 W/System.err(22768): at mono.android.view.View_OnClickListenerImplementor.onClick(View_OnClickListenerImplementor.java:29)
05-29 01:49:10.450 W/System.err(22768): at android.view.View.performClick(View.java:3574)
05-29 01:49:10.450 W/System.err(22768): at android.view.View$PerformClick.run(View.java:14279)
05-29 01:49:10.450 W/System.err(22768): at android.os.Handler.handleCallback(Handler.java:605)
05-29 01:49:10.450 W/System.err(22768): at android.os.Handler.dispatchMessage(Handler.java:92)
05-29 01:49:10.450 W/System.err(22768): at android.os.Looper.loop(Looper.java:137)
05-29 01:49:10.450 W/System.err(22768): at android.app.ActivityThread.main(ActivityThread.java:4441)
05-29 01:49:10.450 W/System.err(22768): at java.lang.reflect.Method.invokeNative(Native Method)
05-29 01:49:10.450 W/System.err(22768): at java.lang.reflect.Method.invoke(Method.java:511)
05-29 01:49:10.450 W/System.err(22768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
05-29 01:49:10.460 W/System.err(22768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
05-29 01:49:10.460 W/System.err(22768): at dalvik.system.NativeStart.main(Native Method)
我已经测试了url,并且没有问题,因为我在代码的其他地方使用了它。我的代码有什么问题?
参考方案
例外?请提供更好的信息。您有一个NetworkOnMainThreadException
,并且没有搜索它,否则您将知道解决方案是将网络代码放入AsyncTask或线程中。
在Java中,我们是否有任何方法可以发现特定字符串是字符串数组的一部分。我可以避免出现一个循环。例如String [] array = {"AA","BB","CC" }; string x = "BB" 我想要一个if (some condition to tell wheth…
在小数点后三位显示秒。 -Java - java我在Java程序中使用毫秒,并将其转换为秒。我的方法执行完此操作后,它将以长格式返回秒。System.out.println("[" + threadID + "]" + " " + "SeqSum res=" + grandTotal + " secs=" …
Java SE 7:执行顺序 - java我正在为Java SE 7考试而学习,并且正在研究示例问题。我似乎无法弄清楚为什么以下程序以x y c g的顺序返回。我理解为什么首先运行x,因为它是一个静态初始化块,但是有人可以解释为什么y在c和g之前运行吗?public class Triangle { Triangle() { System.out.print("c "); } {…
Java RegEx中的单词边界\ b - java我在使用\b作为Java Regex中的单词定界符时遇到困难。对于text = "/* sql statement */ INSERT INTO someTable"; Pattern.compile("(?i)\binsert\b");找不到匹配项Pattern insPtrn = Pattern.compile(&…
System.out.printf不打印整数参数 - java我是Java编程的新手,无法从另一个类返回方法。这两个类都可以编译并成功运行。我可以从一个类中调用一个简单的int,但是当我想计算用户输入的两个输入整数时,我只会得到一个空格。这是我的计算课class calculations { public final int AGE = 53; public int numbers(int num1, int num2…