【问题标题】:Why my app gets 415 http error but postman gets 200?为什么我的应用程序得到 415 http 错误但邮递员得到 200?
【发布时间】:2014-08-03 12:17:11
【问题描述】:

我有一个应用程序需要将许多拍摄的照片上传到服务器。我尝试了很多代码,上面是我最后一次使用的代码。我在 AsyncTask 后面使用它。当我尝试发送文件时,我收到“不支持的媒体类型”415 HTTP 错误。我使用 Chrome 扩展程序 postman 做了一些测试,我可以看到标题是如何制作的:

Content-Disposition: form-data; name="ssss"; filename="beatles-1600x1200.jpg"
Content-Type: image/jpeg

但我看不到这段代码的最终标题。这是我的第二个安卓应用。我的知识贫乏使得解决这种情况变得非常困难。非常欢迎任何帮助!

public String sendOneFile(String url, String fileName)
{
    String responseBody = "";
    File file = new File(fileName);
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
        reqEntity.setContentType("image/jpeg"); //("binary/octet-stream");
        reqEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));
        reqEntity.setChunked(true);
        HttpResponse response = httpclient.execute(httppost);
        int responseCode = response.getStatusLine().getStatusCode();
        switch(responseCode) {
            case 200:
                HttpEntity entity = response.getEntity();
                if(entity != null) {
                    responseBody = EntityUtils.toString(entity);
                }
                break;
            case 415:
                return "(Com ERRO) Media type not supported.";
        }
        //Do something with response...
        return responseBody;
    } catch (Exception e) {
        return "(Com ERRO) " + e.getMessage();
    }
}

【问题讨论】:

    标签: android file http post upload


    【解决方案1】:

    试试这个:

    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.util.Log;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpVersion;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.CoreProtocolPNames;
    import org.apache.http.params.HttpParams;
    import org.apache.http.util.EntityUtils;
    import org.apache.http.entity.mime.MultipartEntity;
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.ProtocolException;
    import java.net.URL;
    
    
    public class HTTPconector {
        private DefaultHttpClient mHttpClient;
        Context context;
    
        //Contrutor para que metodos possam ser usados fora de uma activity
        public HTTPconector(Context context) {
            this.context = context;
        }
    
    
        public HTTPconector() {
            HttpParams params = new BasicHttpParams();
            params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            mHttpClient = new DefaultHttpClient(params);
        }
    
    
        public void ClientPost(String txtUrl, File file){
            try {
    
                HttpPost httppost = new HttpPost(txtUrl);
    
                MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                multipartEntity.addPart("Image", new FileBody(file));
                httppost.setEntity(multipartEntity);
    
                mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
    
            } catch (Exception e) {
                Log.e(HTTPconector.class.getName(), e.getLocalizedMessage(), e);
            }
        }
    
    
    
        //Verifica se a rede esta disponível
        public boolean isNetworkAvailable() {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            // if no network is available networkInfo will be null
            // otherwise check if we are connected
            if (networkInfo != null && networkInfo.isConnected()) {
                return true;
            }
            return false;
        }
    
    
        public String Get(String txtUrl){
            try {
                URL url = new URL(txtUrl);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setReadTimeout(10000);
                con.setConnectTimeout(15000);
                con.setRequestMethod("GET");
                con.setDoInput(true);
                con.connect();
    
                return readStream(con.getInputStream());
    
            }  catch (ProtocolException e) {
                e.printStackTrace();
                return "ERRO: "+e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "ERRO: "+e.getMessage();
            }
        }
    
    
        public String Post(String txtUrl){
            File image;
    
            try {
                URL url = new URL(txtUrl);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setDoInput(true);
                con.setDoOutput(true);
                con.connect();
    
                //con.getOutputStream().write( ("name=" + "aa").getBytes());
    
                return readStream(con.getInputStream());
            } catch (ProtocolException e) {
                e.printStackTrace();
                return "ERRO: "+e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "ERRO: "+e.getMessage();
            }
        }
    
    
        //Usado para fazer conexão com a internet
        public String conectar(String u){
            String resultServer = "";
            try {
                URL url = new URL(u);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                resultServer = readStream(con.getInputStream());
            } catch (Exception e) {
                e.printStackTrace();
                resultServer = "ERRO: "+ e.getMessage();
            }
    
            Log.i("HTTPMANAGER: ", resultServer);
            return resultServer;
        }
    
        //Lê o resultado da conexão
        private String readStream(InputStream in) {
            String serverResult = "";
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
    
                serverResult = reader.toString();
            }   catch (IOException e) {
                e.printStackTrace();
                serverResult = "ERRO: "+ e.getMessage();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        serverResult = "ERRO: "+ e.getMessage();
                    }
                }
            }
            return  serverResult;
        }
    
    
        private class PhotoUploadResponseHandler implements ResponseHandler<Object> {
    
            @Override
            public Object handleResponse(HttpResponse response)throws ClientProtocolException, IOException {
    
                HttpEntity r_entity = response.getEntity();
                String responseString = EntityUtils.toString(r_entity);
                Log.d("UPLOAD", responseString);
    
                return null;
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-05
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2020-02-23
      • 2019-04-01
      • 1970-01-01
      相关资源
      最近更新 更多