【问题标题】:HttpEntity alternate in android?HttpEntity在android中的替代品?
【发布时间】:2025-11-30 20:20:04
【问题描述】:

为了上传图片,我使用 android volley 库向服务器发送多部分请求。我已经为 android Volley 库编写了一些自定义代码。HtppEntity 在这里用作此文件中的一个类,但现在我收到警告,HttpEntity 已被弃用。我碰巧知道HttpurlConnection 是一个替代方案,但我不知道如何在我的代码中替换它?

这是我的代码

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.CharsetUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by JoeyJAL on 2015/3/14.
 */
public class MultiPartRequest extends Request<String> {

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    HttpEntity httpentity;
    private String FILE_PART_NAME = "imageFile";

    private final Response.Listener<String> mListener;
    private final File mFilePart;
    private final Map<String, String> mStringPart;

    public MultiPartRequest(String url, Response.ErrorListener errorListener,
                            Response.Listener<String> listener, File file,
                            Map<String, String> mStringPart) {
        super(Method.POST, url, errorListener);

        this.mListener = listener;
        this.mFilePart = file;
        this.mStringPart = mStringPart;

        entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {
            entity.setCharset(CharsetUtils.get("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        buildMultipartEntity();
        httpentity = entity.build();
    }

    private void buildMultipartEntity() {
        entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/jpeg"), mFilePart.getName()));
        if (mStringPart != null) {
            for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
                entity.addTextBody(entry.getKey(), entry.getValue());
            }
        }
    }

    @Override
    public String getBodyContentType() {
        return httpentity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try
        {
            httpentity.writeTo(bos);
        }
        catch (IOException e)
        {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {

        try {
          System.out.println("Network Response "+ new String(response.data, "UTF-8"));
            return Response.success(new String(response.data, "UTF-8"),
                    getCacheEntry());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.success(new String(response.data), getCacheEntry());
        }
    }

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

【问题讨论】:

  • 欢迎来到 *。这不是一个让其他人免费接手你工作的地方。首先,您需要证明您尝试过某事,并与我们分享。
  • @Rahul 您只会得到问题和问题的答案/解决方案。没有人会在这里做你的工作。
  • 我不是在告诉你我的工作只是询问替换代码。我无法理解@kibzorg
  • 好的,我给你演示一下HttpurlConnection
  • 我只想在你看到我的示例代码的地方有一个代码。我使用 httpentity.writeto(bos);我如何使用 httpurl 连接来做到这一点

标签: java android android-volley multipartform-data android-networking


【解决方案1】:
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000); 
conn.setConnectTimeout(15000); 
conn.setRequestMethod("POST"); 
conn.setDoInput(true); 
conn.setDoOutput(true); 

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1)); 
params.add(new BasicNameValuePair("secondParam", paramValue2)); 
params.add(new BasicNameValuePair("thirdParam", paramValue3)); 

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush(); 
writer.close(); 
os.close(); 

conn.connect(); 

这个 getQuery(List) 将有助于生成您的输出流。您正在上传图像,因此您可以通过替换 getQuery() 函数直接将其更改为输出流。

 private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    { 
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        { 
            if (first)
                first = false;
            else 
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        } 

        return result.toString();
    } 

【讨论】: