当前位置: 首页 > 知识库问答 >
问题:

Android multipart POST http请求415错误

壤驷阳波
2023-03-14

这里是android开发新手。我正在尝试将一个.gpx文件发布到我的web数据库中。但是,我收到http响应错误415。我知道415意味着不正确的内容类型,我尝试使用的API有这段代码…谢谢你的提示!

        // Test that request has correct content type
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

这是我的Http请求类

/**
 * This constructor initializes a new HTTP POST request with content type
 * is set to multipart/form-data
 * @param requestURL
 * @param charset
 * @throws IOException
 */
public MultipartUtility(String requestURL, String charset)
        throws IOException {
    this.charset = charset;

    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestMethod("POST");

    httpConn.setRequestProperty("Connection", "Keep-Alive");
    httpConn.setRequestProperty("Content-Type", // content type multipart ( FILE)
           "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("Authorization", UserInfo.User.getToken());
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
}

/**
 * Adds a form field to the request
 * @param name field name
 * @param value field value
 */
public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
            .append(LINE_FEED);
    //writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
}

/**
 * Adds a upload file section to the request
 * @param fieldName name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"");
    //Log.i("fileName",fileName);
    writer.append("Content-Type: " + "multipart/form-data; boundary=" + boundary);
    //.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}

/**
 * Adds a header field to the request.
 * @param name - name of the header field
 * @param value - value of the header field
 */
public void addHeaderField(String name, String value) {
    writer.append(name + ": " + value).append(LINE_FEED);
    writer.flush();
    //Log.i("header",name + ": " + value);
}

/**
 * Completes the request and receives response from the server.
 * @return a list of Strings as response in case the server returned
 * status OK, otherwise an exception is thrown.
 * @throws IOException
 */
public List<String> finish() throws IOException {
    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}

这是我的活动

        String requestURL = "url";


        try {
            MultipartUtility multipart = new MultipartUtility(requestURL, charset);

            multipart.addFilePart("filename", File);

            List<String> response = multipart.finish();

            System.out.println("SERVER REPLIED:");

            for (String line : response) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }

这是我从httpbin得到的响应

/*I/system.out:服务器回复:

I/system.out:{

I/system.out:“args”:{},

i/system.out:“data”:“”,

I/system.out:“files”:{

i/system.out:“filename”:“http://www.topografix.com/gpx/1/1\”version=\“1.0\”>\n\n\r\n“

I/system.out:},

I/system.out:“form”:{},

i/system.out:“accept-encoding”:“gzip”,

i/system.out:“authorization”:“bearer”,

i/system.out:“content-length”:“322”,

I/system.out:},

i/system.out:“json”:null,

i/system.out:“origin”:“50.174.210.222”,

//Retrofit2 method
public void uploadFile() {

    OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    okHttpClientBuilder.addInterceptor(interceptor);

    okHttpClientBuilder.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Request original = chain.request();

            okhttp3.Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", UserInfo.User.getToken());

            okhttp3.Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });


    MediaType MEDIA_TYPE_XML = MediaType.parse("application/xml");

    RequestBody filePart = RequestBody.create(MEDIA_TYPE_XML, gpx);

    MultipartBody.Part file = MultipartBody.Part.createFormData("Track", gpx.getName(), filePart);

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("URL")
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClientBuilder.build());

    Retrofit retrofit = builder.build();

    UserClient client = retrofit.create(UserClient.class);

    Call<ResponseBody> call = client.uploadFile(file);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            Log.i("works", call.toString());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.i("Fail", "gg");
        }
    });
}
@Multipart
@POST("Gpx")
Call<ResponseBody> uploadFile(
        @Part MultipartBody.Part File
        );

}

共有1个答案

骆文彬
2023-03-14
    public static <C> C createService(Class<C> cClass) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(UrlManager.Manager.BASE_URL)
                .build();
        return retrofit.create(cClass);
    }

此代码创建一个工厂,然后记录所有中间件请求。一旦调用此代码,与请求有关的每个内容将自动记录在logcat中。您可以通过键入OKHTTP进行筛选。

若要使用拦截器,请执行以下操作:includecompile“com.squareup.okhttp3:logging-interceptor:3.3.1”

 类似资料:
  • 我的Spring Rest控制器有问题。我试图发布(PUT)数据从我的客户端(angularJS)到我的服务器(Spring),但每次我试图发送的东西我得到一个错误。 有了Maven,我在SpringAPI中添加了和。我还使用自动将Jackson消息转换器添加到Spring。在我的Spring控制器中,我使用访问Spring的REST方法。 我的REST API控制器: 我尝试过不同类型的消费:

  • 我尝试在jmeter中为用java编写的web服务(Spring MVC Hibernate)实现负载测试。服务器是RESTFull的,客户端(angularjs)与服务器通信。 我想用jmeter HTTP请求记录器转储HTTP请求,就像jmeter用户指南教程一样。 问题是,在web浏览器上使用jmeter作为代理时,我不断收到415 Http错误。因此,该网页在试图发布数据时遇到错误,但失败

  • 我目前正在做一个项目,我需要向spring发送一个POST请求。我已经找了好几个小时的解决方案,但没有找到一个可行的。当我开发该部件时,请求起了作用。问题是,在创建一些新功能(另一个控制器中有两个新endpoint)后,用于创建或更新实体的POST请求停止工作,而不会更改特定区域中的代码。 控制器: 最初,关于消费和生产的部分不在那里,我尝试了它,因为在其他帖子上看到了它,但对情况没有帮助。 传感

  • 这是我向Spotify发出身份验证请求的脚本,但它返回错误。我尝试更改内容类型,但这似乎并没有削减它。这是我的代码:

  • 我正在使用实现一个联系人应用程序。现在,我正试图通过发送以下格式的put请求来更新联系人 我将XML作为字符串发送,作为请求的主体。这是我的xmlString(请求主体) 我写了下面的代码来发送更新联系人的PUT请求。 当我试图在中发送请求时,联系人更新成功。但是当我试图运行上面的程序时,我得到了 400错误请求错误 我不知道我哪里出错了。任何帮助都将不胜感激!

  • 我正在为一个项目使用Hackerrank API。查看官方文档,点击这里! 在他们的网站上有一个使用UNIREST的例子, 由于我使用的是axios,所以我将其转换为类似的axios代码,如下所示: 我希望这只适用于示例中所示的示例,但它给我带来了以下错误: 请求失败,状态代码为400 错误:请求失败,状态代码为400 在createError(createError.js:16) 在sett(s