为什么我的应用程序获得415 http错误但邮差得到200?

时间:2014-06-13 02:33:11

标签: android file http post upload

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

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

但我无法看到这段代码的最终标题。这是我的第二个Android应用程序。我的知识匮乏使解决这种情况变得非常困难。我们非常欢迎任何帮助!

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();
    }
}

1 个答案:

答案 0 :(得分:2)

试试这个:

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;
        }

    }
}