猿问

Android端使用OKHTTP通过MultiPartBody提交数据,服务端该如何写?

//为一个按钮注册的click事件
public void doPost(View v){
    new Thread(){
        @Override
        public void run() {
            L.e(picPath);
            File file=new File(picPath);
            MediaType mediaType= MediaType.parse("application/octet-stream");
            RequestBody requestBody=RequestBody.create(mediaType,file);
            RequestBody multipartBody=new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("username",username)
                    .addFormDataPart("password",password)
                    .addFormDataPart("mIcon",username,requestBody)
                    .build();
            Request request=new Request.Builder().url(mBaseUrl+"getMessage").post(multipartBody).build();
            execute(request);
        }
    }.start();
  //execute方法
private void execute(Request request) {

    Call call=okHttpClient.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            L.e("onFailure :"+e.getMessage());
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            L.e("onResponse :");
            res=response.body().string();
            L.e(res);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mTvResult.setText(res);
                }
            });

        }
    });
}
//服务端
@WebServlet("/getMessage")
public class test extends HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        String userName=request.getParameter("username");
        String password=request.getParameter("password");
        System.out.println(userName+"  "+password);
        File mIcon=new File("E//test_img",userName);
        InputStream is= request.getInputStream();
        FileOutputStream fos=new FileOutputStream(mIcon);
        int len;
        byte [] buf=new byte[3*1024];
        while((len=is.read(buf))!=-1)
        {
            fos.write(buf,0,len);
        }
        fos.flush();
        fos.close();
    }

这样接收到的userName和password都是空。恳请各位大牛指点一二。。。

蜡笔小新的Qe
浏览 7248回答 2
2回答

imooc_幕课网

你客户端发送username值,谁知道是不是空值呢?
随时随地看视频慕课网APP

相关分类

Android
我要回答