Java android中的HttpEntity替代品?

Java android中的HttpEntity替代品?,java,android,android-volley,multipartform-data,android-networking,Java,Android,Android Volley,Multipartform Data,Android Networking,为了上传图像,我使用android volley库向服务器发送多部分请求。我已经为androidVolley库编写了一些自定义代码。HtppEntity在这里用作此文件中的一个类,但现在我收到一条警告,即HttpEntity已被弃用。我碰巧知道HttpurlConnection是另一种选择,但我不知道如何在我的代码中替换它 这是我的代码 import com.android.volley.AuthFailureError; import com.android.volley.NetworkRes

为了上传图像,我使用android volley库向服务器发送多部分请求。我已经为androidVolley库编写了一些自定义代码。
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);
    }
}
import com.android.volley.AuthFailureError;
导入com.android.volley.NetworkResponse;
导入com.android.volley.Request;
导入com.android.volley.Response;
导入com.android.volley.VolleyLog;
导入org.apache.http.HttpEntity;
导入org.apache.http.entity.ContentType;
导入org.apache.http.entity.mime.HttpMultipartMode;
导入org.apache.http.entity.mime.MultipartEntityBuilder;
导入org.apache.http.entity.mime.content.FileBody;
导入org.apache.http.util.CharsetUtils;
导入java.io.ByteArrayOutputStream;
导入java.io.File;
导入java.io.IOException;
导入java.io.UnsupportedEncodingException;
导入java.util.Map;
/**
*JoeyJAL于2015年3月14日创建。
*/
公共类MultiPartRequest扩展请求{
MultipartEntityBuilder实体=MultipartEntityBuilder.create();
HttpEntity HttpEntity;
私有字符串文件\u PART\u NAME=“imageFile”;
私人最终回应。监听器;
私有最终文件mFilePart;
私人最终地图mStringPart;
公共多部分请求(字符串url,Response.ErrorListener ErrorListener,
Response.Listener侦听器,文件,
地图(mStringPart){
super(Method.POST、url、errorListener);
this.mListener=侦听器;
this.mFilePart=文件;
this.mStringPart=mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_兼容);
试一试{
entity.setCharset(CharsetUtils.get(“UTF-8”);
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
buildMultipartEntity();
httpentity=entity.build();
}
私有void buildMultipartEntity(){
entity.addPart(文件名、新文件体(mFilePart、ContentType.create(“image/jpeg”)、mFilePart.getName());
if(mStringPart!=null){
对于(Map.Entry:mStringPart.entrySet()){
entity.addTextBody(entry.getKey(),entry.getValue());
}
}
}
@凌驾
公共字符串getBodyContentType(){
返回httpentity.getContentType().getValue();
}
@凌驾
公共字节[]getBody()抛出AuthFailureError{
ByteArrayOutputStream bos=新建ByteArrayOutputStream();
尝试
{
httpentity.writeTo(bos);
}
捕获(IOE异常)
{
e(“向ByteArrayOutputStream写入IOException”);
}
返回bos.toByteArray();
}
@凌驾
受保护的响应parseNetworkResponse(NetworkResponse响应){
试一试{
System.out.println(“网络响应”+新字符串(Response.data,“UTF-8”);
返回Response.success(新字符串(Response.data,“UTF-8”),
getCacheEntry());
}捕获(不支持的编码异常e){
e、 printStackTrace();
返回Response.success(新字符串(Response.data),getCacheEntry());
}
}
@凌驾
受保护的void deliverResponse(字符串响应){
mListener.onResponse(response);
}
}
URL URL=新URL(“http://yoururl.com");
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
连接设置读取超时(10000);
连接设置连接超时(15000);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“firstParam”,paramValue1));
参数添加(新的BasicNameValuePair(“secondParam”,paramValue2));
参数添加(新的BasicNameValuePair(“第三参数”,参数3));
OutputStream os=conn.getOutputStream();
BufferedWriter=新的BufferedWriter(
新的OutputStreamWriter(操作系统,“UTF-8”);
write(getQuery(params));
writer.flush();
writer.close();
os.close();
连接();
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();
    } 
private String getQuery(列表参数)引发UnsupportedEncodingException
{ 
StringBuilder结果=新建StringBuilder();
布尔值优先=真;
for(NameValuePair对:params)
{ 
如果(第一)
第一个=假;
其他的
结果。追加(&);
append(URLEncoder.encode(pair.getName(),“UTF-8”);
结果。追加(“=”);
append(URLEncoder.encode(pair.getValue(),“UTF-8”);
} 
返回result.toString();
} 

欢迎来到StackOverflow。这不是一个别人将免费接管你工作的地方。首先,你需要展示你尝试过的东西,并与我们分享。@Rahul你只会得到你的问题和问题的答案/解决方案。没有人会在这里做你的工作。我不会告诉你做我的工作只是问替换代码。我无法理解@kibzorgok,让我给你一个HttpUrlConnection的演示。我只想有一个代码,正如你看到我的示例代码。在那里我使用httpentity.writeto(bos);我如何使用httpurl连接来实现这一点
 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();
    }