gpt4 book ai didi

android - MultipartEntityBuilder 从 Android httpurlconnection 发送数据

转载 作者:太空宇宙 更新时间:2023-11-03 13:53:40 25 4
gpt4 key购买 nike

我正在尝试更改 HTTPClient 已弃用的代码,但我在 setEntity 上收到错误,因为它已被删除,而且我不知道如何通过新的 httpConnectionUrl 来 paas MultipartEntityBuilder。我的旧弃用代码 fragment

    try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(imagePostUrl);

for (String fileName : fileNameArrayList) {

File file = new File(fileName);
// 1st

int quality = GeneralUtil.getQualityOfImage(file);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

if (quality <= 25) { // This means image file size is in MB's so we need to avoide out of memory issues.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
try {
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
} catch (OutOfMemoryError E) {
System.gc();
bitmap = GeneralUtil.decodeFile(file);

}

bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;

} else {

try {
bitmap = BitmapFactory.decodeFile(file.getPath());
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError E) {
System.gc();

try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;

bitmap = BitmapFactory.decodeFile(file.getPath(), options);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError ex) {

bitmap = GeneralUtil.decodeFile(file);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
throw new Exception();
}
}
}

byte[] data = bos.toByteArray();
String timeStamp = GeneralUtil.generateTimeStamp();
ByteArrayBody bin = new ByteArrayBody(data, myMobileNo + "_" + userName + "_" + timeStamp + ".jpg");

MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
multiPartEntityBuilder.addPart("uploadedfile1", bin);
multiPartEntityBuilder.addPart("inviteId", new StringBody(inviteIdArrayList.get(0).toString(), Charset.forName("UTF-8")));
post.setEntity(multiPartEntityBuilder.build());
HttpResponse httpResponse = null;
httpResponse = client.execute(post);
InputStream inputStream = null;
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result.add(convertInputStreamToString(inputStream));
else
result.add("Did not work!");
}

我新的无效代码 fragment

    try {
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(imagePostUrl).openConnection()));
httpcon.setDoOutput(true);
for (String fileName : fileNameArrayList) {
File file = new File(fileName);
int quality = GeneralUtil.getQualityOfImage(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (quality <= 25) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
try {
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
} catch (OutOfMemoryError E) {
System.gc();
bitmap = GeneralUtil.decodeFile(file);

}
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;

} else {

try {
bitmap = BitmapFactory.decodeFile(file.getPath());
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError E) {
System.gc();

try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;

bitmap = BitmapFactory.decodeFile(file.getPath(), options);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError ex) {

bitmap = GeneralUtil.decodeFile(file);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
throw new Exception();
}


}
}
byte[] data = bos.toByteArray();
String timeStamp = GeneralUtil.generateTimeStamp();
ByteArrayBody bin = new ByteArrayBody(data, myMobileNo + "_" + userName + "_" + timeStamp + ".jpg");
MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
multiPartEntityBuilder.addPart("uploadedfile1", bin);
multiPartEntityBuilder.addPart("inviteId", new StringBody(inviteIdArrayList.get(0).toString(), Charset.forName("UTF-8")));
httpcon.setEntity(multiPartEntityBuilder.build()); **error**
// Execute POST request to the given URL
// HttpResponse httpResponse = null;
// httpResponse = client.execute(post);
httpcon.setRequestMethod("POST");
httpcon.connect();

最佳答案

这是我建议的替代解决方案:

首先可以引用以下几个库:Volley , Retrofit ...

如果你想使用Volley,你可以引用以下链接:

我与上面第一个链接相关的示例代码

MultipartActivity.java:

public class MultipartActivity extends Activity {

private final Context context = this;
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "apiclient-" + System.currentTimeMillis();
private final String mimeType = "multipart/form-data;boundary=" + boundary;
private byte[] multipartBody;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multipart);

byte[] fileData1 = getFileDataFromDrawable(context, R.drawable.ic_action_android);
byte[] fileData2 = getFileDataFromDrawable(context, R.drawable.ic_action_book);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// the first file
buildPart(dos, fileData1, "ic_action_android.png");
// the second file
buildPart(dos, fileData2, "ic_action_book.png");
// send multipart form data necesssary after file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// pass to multipart body
multipartBody = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}

String url = "http://192.168.1.100/api/postfile";
MultipartRequest multipartRequest = new MultipartRequest(url, null, mimeType, multipartBody, new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
Toast.makeText(context, "Upload successfully!", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Upload failed!\r\n" + error.toString(), Toast.LENGTH_SHORT).show();
}
});

VolleySingleton.getInstance(context).addToRequestQueue(multipartRequest);
}

...

private void buildPart(DataOutputStream dataOutputStream, byte[] fileData, String fileName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
+ fileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);

ByteArrayInputStream fileInputStream = new ByteArrayInputStream(fileData);
int bytesAvailable = fileInputStream.available();

int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];

// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

dataOutputStream.writeBytes(lineEnd);
}

private byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}

多部分请求.java:

class MultipartRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
private final Map<String, String> mHeaders;
private final String mMimeType;
private final byte[] mMultipartBody;

public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = multipartBody;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}

@Override
public String getBodyContentType() {
return mMimeType;
}

@Override
public byte[] getBody() throws AuthFailureError {
return mMultipartBody;
}

@Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}

@Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}

@Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}

当然,您可以在 SO 中找到更多可用的内容。

希望这对您有所帮助!

关于android - MultipartEntityBuilder 从 Android httpurlconnection 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32353466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com