场景: 我正在尝试通过服务中的 HttpURLConnection 发送一些 POST 数据(有进度更新)。 我从图库中抓取一张图片,然后将它发送到带有 2 个参数的 php 服务器; invnum 和密码。
注意: 如果我通过 HttpClient 方法执行此操作,则会在服务器中发送和接收参数和图像,但我无法跟踪上传进度。我看到一些与自定义多部分实体相关的代码,我想尽可能避免引用库
我在 SO 中研究了很多相关问题,但似乎找不到解决方案。以下是我服务中的当前代码。
protected void onHandleIntent(Intent intent) {
String invnum = intent.getStringExtra("invnum");
String uploadURL = intent.getStringExtra("uploadURL");
String imageURI = intent.getStringExtra("imageURI");
uri = Uri.parse(imageURI);
String pass = "password";
//get the actual path of the image residing in the phone
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
//check url
try {
File file = new File(picturePath);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
fileInputStream.close();
String fileName = file.getName();
URL url = new URL(uploadURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setChunkedStreamingMode(1024);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)");
connection.setRequestProperty("image", fileName);
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
//send multipart form data (required) for file
outputStream.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
//outputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + lineEnd);
//outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
//outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);
outputStream.writeBytes("Content-Length: " + file.length() + lineEnd);
outputStream.writeBytes(lineEnd);
int bufferLength = 1024;
for (int i = 0; i < bytes.length; i += bufferLength) {
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int)((i / (float) bytes.length) * 100));
receiver.send(UPDATE_PROGRESS, resultData);
if (bytes.length - i >= bufferLength) {
outputStream.write(bytes, i, bufferLength);
} else {
outputStream.write(bytes, i, bytes.length - i);
}
}
//end output
outputStream.writeBytes(lineEnd);
//write more parameters other than the file
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
//outputStream.writeBytes(twoHyphens + boundary + lineEnd); //less twohyphens
outputStream.writeBytes("Content-Disposition: form-data; name=\"invnum\"" + lineEnd);
//outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
//outputStream.writeBytes("Content-Length: " + invnum.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(invnum + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"pass\"" + lineEnd);
//outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
//outputStream.writeBytes("Content-Length: " + pass.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(pass + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
outputStream.flush();
outputStream.close();
//input ignored for now
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
运行应用程序时,进度反射(reflect)得很好,但在检查我的服务器时,根本没有文件上传。实际上服务器没有发送或接收数据。有谁知道可能导致此问题的原因是什么?下面是我的服务器代码。
$pass = $_POST['pass'];
$invnum = $_POST['invnum'];
$image = $_POST['image'];
if ($pass == 'password') {
//do something
}
更新: 首先,我从 HTTPURLConnection 收到 404 错误。我的网址看起来像“http://www.xyz.com/upload.php”。 更新前一句,通过删除“setChunkedStreamingMode”,我能够成功将参数上传到服务器但不是图像!我很接近!
最佳答案
终于成功了...
行“connection.setChunkedStreamingMode(1024);”导致问题。删除后,参数和文件上传成功。还有一个小问题,上传进度不准确。返回的进度实际上是缓冲区被填满,即使是 3MB 的图像也几乎是瞬时的。进度到100后,文件仍在后台上传。猜猜这将是另一个问题。
关于php - 通过 HttpURLConnection 将参数和图像上传到 PHP 服务器 (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19262817/
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru