java.net.URLConnection
在这里经常询问使用情况,Oracle教程对此非常简洁.
该教程基本上只显示了如何触发GET请求并读取响应.它没有解释如何使用它来执行POST请求,设置请求标头,读取响应标头,处理cookie,提交HTML表单,上传文件等.
那么,我如何使用java.net.URLConnection
触发和处理"高级"HTTP请求?
在android中,如何使用http将文件(数据)从移动设备发送到服务器.
我正在尝试新的Gmail API,示例使用java.nio.file包中的类,ei Files
和FileSystems
.
这些类是在Java jdk 1.7中引入的,因为我在我的Android应用程序中运行jdk 1.7.0_65,我不知道为什么Android Studio找不到这些类.
进口是:
import java.nio.file.FileSystems;
import java.nio.file.Files;
Run Code Online (Sandbox Code Playgroud)
我的build.gradle文件当然告诉系统像这样使用v.1.7
android {
compileSdkVersion 19
buildToolsVersion '20'
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Run Code Online (Sandbox Code Playgroud)
我指向jdk的正确目录:
jdk列在"外部库"部分中:
如果我浏览Java文件,我甚至可以找到java.nio.file.Files和.FileSystems:
现在,****正在发生什么!?根据我的理解,我在这里做的一切,有什么建议吗?
我不知道html是如何工作的.我想要做的是与以下内容完全类似,但在android上
<body>
<form action="<%= some_url %>" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="Submit">
</form>
</body>
Run Code Online (Sandbox Code Playgroud)
我尝试了以下代码 -
private static void postToUrl(String url_to_upload_on,
String file_name_with_ext, byte[] byteArray) {
String attachmentName = "file";
String attachmentFileName = file_name_with_ext;
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try{
URL url = new URL(url_to_upload_on);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(
connection.getOutputStream());
request.writeBytes(twoHyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; …
Run Code Online (Sandbox Code Playgroud) 我正在分享使用HttpURLConnection发送带参数的图像,音频或视频文件的解决方案.参数可以是(纯字符串或JSON).
(Android客户端到PHP后端)
场景:必须上传媒体文件(带参数的音频,视频和图像).
媒体文件将存储在服务器文件夹中,参数将存储到db.
我遇到了一个问题,即在参数丢失时图像上传成功.
找到了潜在的解
如此推荐选择HttpURLConnection而不是Httpclient
您可能想知道,哪个客户最好?
Apache HTTP客户端在Eclair和Froyo上的错误更少.它是这些版本的最佳选择.
对于姜饼和更好的,HttpURLConnection是最好的选择.其简单的API和小巧的尺寸使其非常适合Android.透明压缩和响应缓存可减少网络使用,提高速度并节省电池电量.新的应用程序应该使用HttpURLConnection; 这是我们将继续投入精力的地方.
Android代码:
public int uploadFile(final String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new …
Run Code Online (Sandbox Code Playgroud) 我正在将应用升级到org.apache.http
不推荐使用的API 23 .
我当前(已弃用)的代码如下所示:
HttpClient httpClient = new DefaultHttpClient();
File file = new File(attr.Value);
String url = server_url;
HttpPost request = new HttpPost(url);
FileEntity fileEntity = new FileEntity(file, "image/png");
request.setEntity(fileEntity);
HttpResponse response = httpClient.execute(request);
String output = getContent(response.getEntity().getContent());
Run Code Online (Sandbox Code Playgroud)
我已经找到了一些关于如何使用它的建议HttpURLConnection
,但它们比当前的解决方案(不能再使用)复杂得多.我正在谈论用于执行与上述相同功能的许多代码行.
有没有人有一个很好的固定更短的解决方案呢?
java android httpurlconnection apache-commons-httpclient android-6.0-marshmallow
我已经坚持了一段时间.我有一个异步任务,将图像上传到Web服务器.工作良好.
我为此设置了一个进度条对话框.我的问题是如何准确更新进度条.我尝试的所有东西都会导致它从一步到0-100.如果需要5秒或2分钟则无关紧要.上传完成后,栏会挂到0然后点击100.
这是我的doInBackground代码.任何帮助表示赞赏.
编辑:我更新了下面的代码,包括整个AsynchTask
private class UploadImageTask extends AsyncTask<String,Integer,String> {
private Context context;
private String msg = "";
private boolean running = true;
public UploadImageTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Uploading photo, please wait.");
dialog.setMax(100);
dialog.setCancelable(true);
}
@Override
protected void onPreExecute() {
dialog.show();
dialog.setOnDismissListener(mOnDismissListener);
}
@Override
protected void onPostExecute(String msg){
try {
// prevents crash in rare case where activity finishes before dialog
if (dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
} …
Run Code Online (Sandbox Code Playgroud) 在我的项目中,我必须严格使用HttpURLConnection类
我有以下代码,我从互联网上获得
MultipartEntity multiPart = new MultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null Chartset.forName("UTF-8");
File f = new File("/home/abhishek/foo.docx");
FileBody fb = new FileBody(f);
multiPart.addPart("file", fb);
HttpPost post = new HttpPost();
post.setHeader("ENCTYPE", "multipart/form-data");
post.setEntity(multiPart);
Run Code Online (Sandbox Code Playgroud)
问题是我不能使用HttpPost ...在我的项目中只有HttpURLConnection类有效!
所以我需要将上面的代码翻译成HttpURLConnection.
我在HttpUrlConnection上找不到类似于setEntity的东西.
编辑::
基于以下建议.我有这个代码
public class RESTFileUpload {
public static void main(String[] args) throws Exception {
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("domain\\user", "Password".toCharArray());
}
});
String filePath = "/home/abhishek/Documents/HelloWorld.docx";
String fileName = "HelloWorld.docx";
String fileNameShort = "HelloWorld";
String urlStr = "https://sp.company.com/sites/abhi_test/_vti_bin/listdata.svc/SharedDocuments/RootFolder/Files/add(url=@TargetFileName,overwrite='true')&@TargetFileName=" + fileName;
String …
Run Code Online (Sandbox Code Playgroud) 我正在开发小型 android 应用程序,我想在其中将图像从我的 android 设备上传到我的服务器。我正在使用HttpURLConnection
它。
我正在通过以下方式执行此操作:
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "image/jpeg");
connection.setRequestMethod(method.toString());
ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(data);
bout.close();
Run Code Online (Sandbox Code Playgroud)
我正在使用,ByteArrayOutputStream
但我不知道如何使用我的 httpurlconnection 传递该数据。这是传递原始图像数据的正确方法吗?我只想发送包含图像数据的字节数组。没有转换或没有多部分发送。我的代码工作正常,没有任何错误,但我的服务器给了我答复
{"error":"Mimetype not supported: inode\/x-empty"}
我用 httpclient 做了这个,setEntity
它可以很好地工作。但我想使用 urlconnection。
难道我做错了什么?这该怎么做?谢谢你。
android ×7
java ×5
http ×2
blobstore ×1
content-type ×1
file ×1
file-io ×1
httprequest ×1
java-7 ×1
mime-types ×1
post ×1
progress-bar ×1