我需要向 PHP 服务器发送一个文件和一些数据。我为此使用一个线程和一个每 15 分钟执行一次的服务。当网络可用时它工作正常。但是当不在网络中时它停止发送文件(如果文件的大小相对较大)。在应用日志后,我看到,未获取来自服务器的响应。它得到了 struk。此外,它在第一次尝试发送文件时发送 Unknownhost 异常.可能是什么问题?请帮助。
这是代码:-
public void run(){
while (keepRunning){
isRunning = true;
SystemClock.sleep(900000);
File tempFile = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/", "barcode_log");
File tempFile1 = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/", "data_log.txt");
if(tempFile.exists())
{
Log.d(TAG," in keep running");
String[] files = (new File(Environment.getExternalStorageDirectory() + PATH)).list();
Log.d(TAG," below file list");
SimpleDateFormat df3 = new SimpleDateFormat("yyyyMMdd_HHmmss");
Date curDate = new Date();
String s= "data_log";//df3.format(curDate);
Log.d("log",files[0]);
File file = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/","barcode_log");
String new_file_name =s+".txt";
// File (or directory) with new name
File file2 = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/",new_file_name);
// Rename file (or directory)
if(!tempFile1.exists()){
boolean success = file.renameTo(file2);
Log.d(TAG," file name created");
if (success) {
// File was not successfully renamed
Log.d(TAG," file rename success");
}
else
{
Log.d(TAG," file not rename success");
}
}
ts.writeBarcodeToFile(" S L", "");
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/"+new_file_name;//zipName;
String urlServer = "http://xyz.com/xyz.php?fname="+s+".txt";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "V2ymHFg03ehbqgZCaKO6jy";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 2*1024*1024;
FileInputStream fileInputStream=null;
try
{
ts.writeBarcodeToFile(" in try sl", "");
fileInputStream = new FileInputStream(new File(pathToOurFile) );
InetAddress iAddr = InetAddress.getByName("http://xyz.com");
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setConnectTimeout(20000);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
ts.writeBarcodeToFile("before while sl ", "");
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
ts.writeBarcodeToFile("after while sl ", "");
// Responses from the server (code and message)
try{
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseCode==200)
{
ts.writeBarcodeToFile("in if server response ", "");
//ts.writeBarcodeToFile("L S", "");
tempFile1.delete();
}
else
{
ts.writeBarcodeToFile("in else server response ", "");
ts.writeBarcodeToFile(serverResponseCode+"", "");
}
}
catch(Exception e)
{
try{
outputStream.flush();
outputStream.close();
}
catch(Exception ex)
{
}
ts.writeBarcodeToFile("in url catch response "+e.toString(), "");
connection.disconnect();
}
ts.writeBarcodeToFile("after server sl ", "");
fileInputStream.close();
outputStream.flush();
outputStream.close();
ts.writeBarcodeToFile("after close sl ", "");
}
catch (java.net.SocketTimeoutException e) {
try{
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch(Exception ex)
{
}
ts.writeBarcodeToFile("in socketex sl "+e.toString(), "");
connection.disconnect();
}
catch (java.io.IOException e)
{
try{
fileInputStream.close();
outputStream.flush();
outputStream.close();
connection.disconnect();
}
catch(Exception ex)
{
}
ts.writeBarcodeToFile("in ioex sl "+e.toString(), "");
}
catch (Exception ex)
{
try{
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch(Exception exy)
{
}
ts.writeBarcodeToFile("in catch sl "+ex.toString(), "");
connection.disconnect();
//Exception handling
}
//System.gc();
}
}
isRunning = false;
}
最佳答案
此问题与连接有关。我还看到当我们使用 wifi 时,我们没有遇到未知的主机异常错误(除非我拔下设备)。 当设备仅在 3g/4g 上时,我们遇到了未知的主机异常错误。
您可以尝试对上传类似线程的可恢复支持 resume uploads using HTTP?
或编写您自己的协议(protocol)(分块上传)。
关于android - 数据传输时出现未知主机异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14364400/
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd
我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge
我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案