- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在使用 MultiPartRequester 类将多部分图像上传到服务器,但我发现其中的某些部分已被弃用。例如 HttpConnectionParams 、 getConnectionManager() 等,所以任何人都有新的解决方案,不建议使用新的文件上传 API 级别?
我正在使用这个代码。
public class MultiPartRequester {
private Map<String, String> map;
private AsyncTaskCompleteListener mAsynclistener;
private int serviceCode;
private HttpClient httpclient;
private Activity activity;
private AsyncHttpRequest request;
private static final String TAG = "MultiPartRequester";
public MultiPartRequester(Activity activity, Map<String, String> map,
int serviceCode, AsyncTaskCompleteListener asyncTaskCompleteListener) {
this.map = map;
this.serviceCode = serviceCode;
this.activity = activity;
}
class AsyncHttpRequest extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
map.remove("url");
try {
HttpPost httppost = new HttpPost(urls[0]);
httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(
httpclient.getParams(), 600000);
MultipartEntityBuilder builder = MultipartEntityBuilder
.create();
for (String key : map.keySet()) {
if (key.equalsIgnoreCase(AndyConstants.Params.PICTURE)) {
File f = new File(map.get(key));
builder.addBinaryBody(key, f,
ContentType.MULTIPART_FORM_DATA, f.getName());
} else {
builder.addTextBody(key, map.get(key), ContentType
.create("text/plain", MIME.UTF8_CHARSET));
}
AppLog.Log(TAG, key + "---->" + map.get(key));
}
httppost.setEntity(builder.build());
ActivityManager manager = (ActivityManager) activity
.getSystemService(Context.ACTIVITY_SERVICE);
if (manager.getMemoryClass() < 25) {
System.gc();
}
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(
response.getEntity(), "UTF-8");
reurn responseBody;
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError oume) {
System.gc();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
return null;
}
@Override
protected void onPostExecute(String response) {
if (mAsynclistener != null) {
mAsynclistener.onTaskCompleted(response, serviceCode);
}
}
}
public void cancelTask() {
request.cancel(true);
AppLog.Log(TAG, "task is canelled");
}
}
最佳答案
这是 FileUploadMultipartRequest 类:
/**
* Multipart request for sending files over http
* also can return generic type of response data
* @param <T> the type of data for http responses
*/
public class FileUploadMultipartRequest<T> extends BaseRequest<T>
{
private static final MediaType JSON = MediaType.parse("application/json");
private File[] files;
private String jsonString;
private RequestBody requestBody;
public FileUploadMultipartRequest(String url, Map<String, String> headers, String jsonString, OnEmptyResponseListener listener, ErrorTypeListener errorListener, File... files)
{
super(Method.POST, url, headers, listener, new ErrorListenerImpl(errorListener));
this.jsonString = jsonString;
this.files = files;
}
public FileUploadMultipartRequest(String url, Map<String, String> headers, String jsonString, Type responseType, Response.Listener listener, ErrorTypeListener errorListener, File... files)
{
super(Method.POST, url, headers, responseType, listener, new ErrorListenerImpl(errorListener));
this.jsonString = jsonString;
this.files = files;
}
@Override
public String getBodyContentType()
{
return buildMultipartEntity().contentType().toString();
}
@Override
public byte[] getBody() throws AuthFailureError
{
Buffer buffer = new Buffer();
try
{
buildMultipartEntity().writeTo(buffer);
} catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return buffer.readByteArray();
}
private RequestBody buildMultipartEntity()
{
if (requestBody == null)
{
MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
multipartBuilder.addPart(
Headers.of("Content-Disposition", "form-data; name=json-part"),
RequestBody.create(JSON, jsonString));
for (File file : files)
{
String contentType = URLConnection.guessContentTypeFromName(file.getName());
multipartBuilder.addFormDataPart("files-part", file.getName(),
RequestBody.create(MediaType.parse(contentType), file));
}
requestBody = multipartBuilder.build();
}
return requestBody;
}
}
这是 BaseRequest 类:
/**
* this a abstract request class for handling http http responses
* note : all volley request should extend this class for http request
*
* @param <T> the type of data for http responses
*/
public abstract class BaseRequest<T> extends Request<T>
{
private final Map<String, String> headers;
/**
* the type response that {@link com.android.volley.Response.Listener} should return
*/
private Type responseType;
/**
* generic listener for successful http request
*/
private Response.Listener<T> listener;
/**
* constructor for request that returns data type {@link T}
*
* @param method http verb e.g. POST, GET & etc
* @param url request URL
* @param headers http headers
* @param responseType type of data that response should return
* @param listener event for successful request
* @param errorListener event for failed request
*/
public BaseRequest(int method, String url, Map<String, String> headers, Type responseType, Response.Listener listener, ErrorListenerImpl errorListener)
{
super(method, url, errorListener);
this.headers = headers;
this.responseType = responseType;
//noinspection unchecked
this.listener = listener;
}
/**
* constructor for requests with no returning data
* @param method http verb e.g. POST, GET & etc
* @param url request URL
* @param headers http headers
* @param onEmptyResponseListener event for successful request (but no data return)
* @param errorListener event for failed request
*/
public BaseRequest(int method, String url, Map<String, String> headers, OnEmptyResponseListener onEmptyResponseListener, ErrorListenerImpl errorListener)
{
super(method, url, errorListener);
this.headers = headers;
//noinspection unchecked
listener = new OnEmptyResponseImpl(onEmptyResponseListener);
}
protected Response<T> parseNetworkResponse(NetworkResponse response)
{
// if response type is null so just pass null to success event
if (this.responseType == null && new String(response.data).isEmpty())
{
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
}
// if response type is specified
try
{
Gson gson = new Gson();
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
// we use GSON to reflect response data to the generic type and pass to success event
T parseObject = gson.fromJson(json, responseType);
return Response.success(parseObject, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e)
{
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e)
{
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(T response)
{
if (listener != null)
{
// call successful response event when listener not empty
listener.onResponse(response);
}
}
@Override
protected void onFinish()
{
super.onFinish();
listener = null;
}
/**
* this class forward response event to {@link com.khosravi.mehrdadz.garagesale.Network.RequestType.BaseRequest.OnEmptyResponseListener}
* when volley {@link com.android.volley.Response.Listener} is called
*/
private static class OnEmptyResponseImpl implements Response.Listener
{
OnEmptyResponseListener onEmptyResponseListener;
/**
* @param onEmptyResponseListener interface for response with not data return
*/
public OnEmptyResponseImpl(OnEmptyResponseListener onEmptyResponseListener)
{
this.onEmptyResponseListener = onEmptyResponseListener;
}
/**
* we call {@link com.khosravi.mehrdadz.garagesale.Network.RequestType.BaseRequest.OnEmptyResponseImpl#onEmptyResponseListener}
* when volley listener is class so no null object passed to the event
*
* @param response
*/
@Override
public void onResponse(Object response)
{
onEmptyResponseListener.OnEmptyResponse();
}
}
/**
* interface for http response with no returning data
*/
public interface OnEmptyResponseListener
{
void OnEmptyResponse();
}
public Map<String, String> getHeaders() throws AuthFailureError
{
return this.headers != null ? this.headers : super.getHeaders();
}
}
这是 GsonRequest 类:
@SuppressWarnings("JavaDoc")
/**
* Gson request that return generic type of response data
* @param <T> the type of data for http responses
*/
public class GsonRequest<T> extends BaseRequest<T>
{
protected static final String PROTOCOL_CHARSET = "utf-8";
/**
* Content type for request.
*/
private static final String PROTOCOL_CONTENT_TYPE =
String.format("application/json; charset=%s", PROTOCOL_CHARSET);
/**
* message body of http request
*/
private final String requestBody;
/**
* Request return response object of Type {@link T}
* @param url
* @param headers
* @param type
* @param listener
* @param errorListener
*/
public GsonRequest(String url, Map<String, String> headers, Type type, Listener<T> listener, ErrorTypeListener errorListener)
{
super(Method.GET, url, headers, type, listener, new ErrorListenerImpl(errorListener));
requestBody = null;
}
/**
* Request return response object of Type {@link T}
* @param url
* @param headers
* @param jsonObject json object to send with request
* @param type
* @param listener
* @param errorListener
*/
public GsonRequest(String url, Map<String, String> headers, JSONObject jsonObject, Type type, Listener<T> listener, ErrorTypeListener errorListener)
{
super(Method.POST, url, headers, type, listener, new ErrorListenerImpl(errorListener));
this.requestBody = jsonObject == null ? null : jsonObject.toString();
}
/**
* Request return empty response
* @param url
* @param headers
* @param jsonObject json object to send with request
* @param listener
* @param errorListener
*/
public GsonRequest(String url, Map<String, String> headers, JSONObject jsonObject, OnEmptyResponseListener listener, ErrorTypeListener errorListener)
{
super(Method.POST, url, headers, listener, new ErrorListenerImpl(errorListener));
this.requestBody = jsonObject == null ? null : jsonObject.toString();
}
/**
* Request return empty response
* @param url
* @param headers
* @param listener
* @param errorListener
*/
public GsonRequest(String url, Map<String, String> headers, BaseRequest.OnEmptyResponseListener listener, ErrorTypeListener errorListener)
{
super(Method.GET, url, headers, listener, new ErrorListenerImpl(errorListener));
requestBody = null;
}
@Override
public String getBodyContentType()
{
return PROTOCOL_CONTENT_TYPE;
}
@Override
public byte[] getBody()
{
try
{
return requestBody == null ? null : requestBody.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee)
{
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, PROTOCOL_CHARSET);
return null;
}
}
}
示例鳕鱼:
public class MyRequest
{
public MyRequest(Context context)
{
volleySingleton = VolleySingleton.getInstance(context);
}
private static final String INSERT_NEW_PIC = "INSERT_NEW_PIC";
public void UploadNewPic(File[] Images, BaseRequest.OnEmptyResponseListener listener, ErrorTypeListener errorListener)
{
FileUploadMultipartRequest fileUploadMultipartRequest = new FileUploadMultipartRequest("url", null, null, listener, errorListener,Images);
volleySingleton.addToRequestQueue(fileUploadMultipartRequest, INSERT_NEW_PIC);
}
}
您可以向我的请求添加更多请求并在任何地方调用它。像这样:
MyRequest myRequest;
private HashMap<FrameLayout,File> Images;
myRequest = new MyRequest(context);
Images = new HashMap<>();
myRequest.UploadNewPic(Images.values().toArray(new File[Images.values().size()]), new BaseRequest.OnEmptyResponseListener()
{
@Override
public void OnEmptyResponse()
{
Toast.makeText(getApplicationContext(), "added pics successfully", Toast.LENGTH_LONG).show();
finish();
}
}, new ErrorTypeListener()
{
@Override
public void onError(ErrorType errorType)
{
}
});
服务器端代码(.net):
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
//below only allows images and pdf files to be uploaded.
public override Stream GetStream(HttpContent parent, System.Net.Http.Headers.HttpContentHeaders headers)
{
// following line handles other form fields other than files.
if (String.IsNullOrEmpty(headers.ContentDisposition.FileName)) return base.GetStream(parent, headers);
// restrict what filetypes can be uploaded
List<string> extensions = new List<string> { "png", "gif",
"jpg", "jpeg", "tiff", "pdf", "tif", "bmp","doc","docx","ods","xls","odt","csv","txt","rtf" };
var filename = headers.ContentDisposition.FileName.Replace("\"", string.Empty); // correct for chrome.
//make sure it has an extension
if (filename.IndexOf('.') < 0)
{
return Stream.Null;
}
//get the extension
var extension = filename.Split('.').Last();
//Return stream if match otherwise return null stream.
return extensions.Contains(extension) ? base.GetStream(parent, headers) : Stream.Null;
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";
name = name.Replace("\"", string.Empty);
//name = (Guid.NewGuid()).ToString() +System.IO.Path.GetExtension(name); //this is here because Chrome submits files in quotation marks which get treated as part of the filename and get escaped
name = Path.GetRandomFileName().Replace(".", string.Empty) + Path.GetExtension(name); //this is here because Chrome submits files in quotation marks which get treated as part of the filename and get escaped
return name;
}
}
公共(public)类 ImageRouteHandler :
IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var filename = requestContext.RouteData.Values["filename"] as string;
var section = requestContext.RouteData.Values["section"] as string;
if (string.IsNullOrEmpty(filename) && string.IsNullOrEmpty(section))
{
// return a 404 HttpHandler here
requestContext.HttpContext.Response.StatusCode = 404;
requestContext.HttpContext.Response.End();
return null;
}
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.Cache.SetMaxAge(TimeSpan.FromSeconds(500000));
requestContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.Public);
requestContext.HttpContext.Response.ContentType = GetContentType(filename);
// find physical path to image here.
var path = GetPath(section);
if (string.IsNullOrEmpty(path))
{
// return a 404 HttpHandler here
requestContext.HttpContext.Response.StatusCode = 404;
requestContext.HttpContext.Response.End();
return null;
}
var filepath = requestContext.HttpContext.Server.MapPath(path + filename);
requestContext.HttpContext.Response.WriteFile(filepath);
requestContext.HttpContext.Response.End();
return null;
}
private static string GetPath(string section)
{
switch (section)
{
case "user":
return "~/Resources/Users/";//where you want save pics in project
}
return "";
}
private static string GetContentType(string path)
{
switch (Path.GetExtension(path))
{
case ".bmp":
return "Image/bmp";
case ".gif":
return "Image/gif";
case ".jpg":
return "Image/jpeg";
case ".png":
return "Image/png";
}
return "";
}
}
并像这样更改您的 RouteConfige:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// proccess all for protected resources with ImageRouteHandler
routes.Add("ImagesRoute", new Route("res/{section}/{filename}", new ImageRouteHandler()));
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
服务器端示例代码:
public interface IUserManagement
{
void UploadNewPics( IEnumerable<string> imageUrls);
}
public class UserManagement : IUserManagement
{
public void UploadNewPics(IEnumerable<string> imageUrls)
{
using (var ctx = new Context())
{
foreach (var imageUrl in imageUrls)
{
//save to data base
.
.
.
}
try
{
ctx.SaveChanges();
}
catch (Exception e)
{
throw;
}
}
}
}
public class UserApiController : ApiController
{
[HttpPost]
public async Task<IHttpActionResult> UploadNewPics()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/Resources/Users/");
var provider = new CustomMultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
IUserManagement userManagement = new UserManagement();
var imageUrls = provider.FileData.Select(x=> Path.GetFileName(x.LocalFileName));
//userManagement.UploadUserImage(uploadImageJson, Path.GetFileName(imageFile.LocalFileName), (long)imageFile.Headers.ContentLength);
userManagement.UploadNewPics(imageUrls);
}
catch (Exception e)
{
return InternalServerError();
}
return Ok();
}
}
关于在新的 api 中不推荐使用 HttpConnectionParams 的 Android 多部分图像上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36513174/
我在网上搜索但没有找到任何合适的文章解释如何使用 javascript 使用 WCF 服务,尤其是 WebScriptEndpoint。 任何人都可以对此给出任何指导吗? 谢谢 最佳答案 这是一篇关于
我正在编写一个将运行 Linux 命令的 C 程序,例如: cat/etc/passwd | grep 列表 |剪切-c 1-5 我没有任何结果 *这里 parent 等待第一个 child (chi
所以我正在尝试处理文件上传,然后将该文件作为二进制文件存储到数据库中。在我存储它之后,我尝试在给定的 URL 上提供文件。我似乎找不到适合这里的方法。我需要使用数据库,因为我使用 Google 应用引
我正在尝试制作一个宏,将下面的公式添加到单元格中,然后将其拖到整个列中并在 H 列中复制相同的公式 我想在 F 和 H 列中输入公式的数据 Range("F1").formula = "=IF(ISE
问题类似于this one ,但我想使用 OperatorPrecedenceParser 解析带有函数应用程序的表达式在 FParsec . 这是我的 AST: type Expression =
我想通过使用 sequelize 和 node.js 将这个查询更改为代码取决于在哪里 select COUNT(gender) as genderCount from customers where
我正在使用GNU bash,版本5.0.3(1)-发行版(x86_64-pc-linux-gnu),我想知道为什么简单的赋值语句会出现语法错误: #/bin/bash var1=/tmp
这里,为什么我的代码在 IE 中不起作用。我的代码适用于所有浏览器。没有问题。但是当我在 IE 上运行我的项目时,它发现错误。 而且我的 jquery 类和 insertadjacentHTMl 也不
我正在尝试更改标签的innerHTML。我无权访问该表单,因此无法编辑 HTML。标签具有的唯一标识符是“for”属性。 这是输入和标签的结构:
我有一个页面,我可以在其中返回用户帖子,可以使用一些 jquery 代码对这些帖子进行即时评论,在发布新评论后,我在帖子下插入新评论以及删除 按钮。问题是 Delete 按钮在新插入的元素上不起作用,
我有一个大约有 20 列的“管道分隔”文件。我只想使用 sha1sum 散列第一列,它是一个数字,如帐号,并按原样返回其余列。 使用 awk 或 sed 执行此操作的最佳方法是什么? Accounti
我需要将以下内容插入到我的表中...我的用户表有五列 id、用户名、密码、名称、条目。 (我还没有提交任何东西到条目中,我稍后会使用 php 来做)但由于某种原因我不断收到这个错误:#1054 - U
所以我试图有一个输入字段,我可以在其中输入任何字符,但然后将输入的值小写,删除任何非字母数字字符,留下“。”而不是空格。 例如,如果我输入: 地球的 70% 是水,-!*#$^^ & 30% 土地 输
我正在尝试做一些我认为非常简单的事情,但出于某种原因我没有得到想要的结果?我是 javascript 的新手,但对 java 有经验,所以我相信我没有使用某种正确的规则。 这是一个获取输入值、检查选择
我想使用 angularjs 从 mysql 数据库加载数据。 这就是应用程序的工作原理;用户登录,他们的用户名存储在 cookie 中。该用户名显示在主页上 我想获取这个值并通过 angularjs
我正在使用 autoLayout,我想在 UITableViewCell 上放置一个 UIlabel,它应该始终位于单元格的右侧和右侧的中心。 这就是我想要实现的目标 所以在这里你可以看到我正在谈论的
我需要与 MySql 等效的 elasticsearch 查询。我的 sql 查询: SELECT DISTINCT t.product_id AS id FROM tbl_sup_price t
我正在实现代码以使用 JSON。 func setup() { if let flickrURL = NSURL(string: "https://api.flickr.com/
我尝试使用for循环声明变量,然后测试cols和rols是否相同。如果是,它将运行递归函数。但是,我在 javascript 中执行 do 时遇到问题。有人可以帮忙吗? 现在,在比较 col.1 和
我举了一个我正在处理的问题的简短示例。 HTML代码: 1 2 3 CSS 代码: .BB a:hover{ color: #000; } .BB > li:after {
我是一名优秀的程序员,十分优秀!