사진을 업로드할 때 org.apache.http.client.HttpResponseException: Not Foun이 보고됩니다.

WBOY
풀어 주다: 2016-09-12 17:44:41
원래의
1164명이 탐색했습니다.

이미지를 올리자마자 위와 같은 오류가 뜹니다. 잘못된 이미지인데 URL 주소는 맞는데 이미지와 주소가 있는데 업로드가 안되네요. 중단점은 404를 반환합니다.

답글 내용:

이미지를 올리자마자 위와 같은 오류가 뜹니다. 잘못된 이미지인데 URL 주소는 맞는데 이미지와 주소가 있는데 업로드가 안되네요. 중단점은 404를 반환합니다.

404는 클라이언트 문제로 인해 서버가 처리할 수 없다는 의미입니다. https://segmentfault.com/a/11...

httpclient를 지원 중단하고 HttpURLConnection을 사용하는 것이 좋습니다.

<code>import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpConnector {
    public static final int TIMEOUT_MS = 10 * 1000;

    public static String performRequest(String url, File file, Map<String, String> additionalHeaders) {
        String response = null;
        try {
            HashMap<String, String> map = new HashMap<String, String>();
            if (additionalHeaders != null)
                map.putAll(additionalHeaders);
            URL parsedUrl = new URL(url);
            HttpURLConnection connection = openConnection(parsedUrl, file);
            for (String headerName : map.keySet()) {
                connection.addRequestProperty(headerName, map.get(headerName));
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == -1) {
                // -1 is returned by getResponseCode() if the response code could not be retrieved.
                // Signal to the caller that something was wrong with the connection.
                throw new IOException("Could not retrieve response code from HttpUrlConnection.");
            }

            String charset = "utf-8";
            String contentEncoding = null;
            String contentType = null;

            for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
                if (header.getKey() != null) {
                    List<String> headerValueList = header.getValue();
                    if (headerValueList != null && headerValueList.size() > 0) {
                        StringBuffer headerValueSB = new StringBuffer();
                        for (int i = 0; i < headerValueList.size(); i++) {
                            headerValueSB.append(headerValueList.get(i));
                            if (i != headerValueList.size() - 1) {
                                headerValueSB.append(";");
                            }
                        }
                        if (header.getKey().equals("Content-Type")) {
                            contentType = headerValueSB.toString();
                        } else if (header.getKey().equals("Content-Encoding")) {
                            contentEncoding = headerValueSB.toString();
                        }
                    }
                }
            }
            charset = parseCharset(contentType, contentEncoding, charset);

            if (responseCode == 200) {
                //成功
                response = entityFromConnection(connection, charset);
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }

        return response;
    }

    /**
     * Create an {@link HttpURLConnection} for the specified {@code url}.
     */
    protected static HttpURLConnection createConnection(URL url) throws IOException {
        return (HttpURLConnection) url.openConnection();
    }

    /**
     * Opens an {@link HttpURLConnection} with parameters.
     *
     * @param url
     * @return an open connection
     * @throws IOException
     */
    private static HttpURLConnection openConnection(URL url, File file) throws IOException {
        HttpURLConnection connection = createConnection(url);

        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, file);

        return connection;
    }

    private static String parseCharset(String contentType, String contentEncoding,
                                       String defaultCharset) {
        if (contentType != null) {
            String[] params = contentType.split(";");
            for (int i = 1; i < params.length; i++) {
                String[] pair = params[i].trim().split("=");
                if (pair.length == 2) {
                    if (pair[0].equals("charset")) {
                        return pair[1];
                    }
                }
            }
        }

        if (contentEncoding != null && !contentEncoding.equals("")) {
            return contentEncoding;
        }

        return defaultCharset;
    }

    private static String entityFromConnection(HttpURLConnection connection, String charset) throws IOException {
        String data = null;
        InputStream inputStream;
        try {
            inputStream = connection.getInputStream();
        } catch (IOException ioe) {
            inputStream = null;
        }
        if (inputStream != null) {
            data = readData(inputStream, charset);
        }

        return data;
    }

    private static String readData(InputStream inSream, String charsetName) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inSream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inSream.close();
        return new String(data, charsetName);
    }

    private static void addBodyIfExists(HttpURLConnection connection, File file) {
        try {
            if (file != null) {
                connection.setDoOutput(true);
                connection.addRequestProperty("Content-Type", "application/octet-stream; charset=utf-8");
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                FileInputStream fStream = new FileInputStream(file);
                /* 设定每次写入1024bytes */
                try {
                    int bufferSize = 1024;
                    byte[] buffer = new byte[bufferSize];
                    int length = -1;
                /* 从文件读取数据到缓冲区 */
                    while ((length = fStream.read(buffer)) != -1) {
                        /* 将数据写入DataOutputStream中 */
                        out.write(buffer, 0, length);
                    }
                } finally {
                    fStream.close();
                    out.flush();
                    out.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}</code>
로그인 후 복사

호출: 문자열 응답 = HttpConnector.performRequest(uploadUrl, file, null);

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!