You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中通过Content-Type: application/octet-stream向API发资源及POST请求排障

PHP: Sending application/octet-stream Requests & Fixing Corrupted Image Downloads

Hey there! Let's work through your two PHP questions one by one to get you sorted out.

1. How to Send a Resource to an API with Content-Type: application/octet-stream in PHP

The most reliable way to handle this is with cURL—it gives you full control over request headers and binary data handling. Here's a straightforward, tested example:

// 1. Read your target file (binary-safe by default with file_get_contents)
$filePath = '/path/to/your/resource.jpg';
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
    die("Oops, couldn't read the file at $filePath");
}

// 2. Define your API endpoint
$apiEndpoint = 'https://your-target-api.com/upload';

// 3. Initialize and configure cURL
$ch = curl_init($apiEndpoint);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/octet-stream',
    // Add any required headers here (e.g., auth tokens, content length)
    // 'Authorization: Bearer your-api-token',
    // 'Content-Length: ' . strlen($fileContent)
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Ensure binary data is transferred without modification
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

// 4. Execute the request and handle results
$response = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    die("cURL error: " . curl_error($ch));
}
curl_close($ch);

// Verify success and debug
echo "Request status: $httpStatus\n";
echo "API response: $response\n";

This code reads your file in binary mode, sets the correct Content-Type header, and ensures raw binary data is sent to the API unaltered.

2. Fixing Corrupted Downloaded Images After Reproducing the POST Request

If your downloaded image won't open, it's almost always due to mishandling binary data or missing critical details from your original request screenshot. Here are the most common issues and fixes:

Common Mistakes & Solutions

  • Incorrect file handling: Using text-mode functions (like fopen('file.jpg', 'r') instead of rb) to read/save files will corrupt binary data via line-ending conversion. Stick with file_get_contents/file_put_contents (binary-safe by default) or use binary mode explicitly.
  • Missing cURL settings: Forgetting CURLOPT_BINARYTRANSFER can mangle binary data, especially in older PHP versions. Always include this option when sending/receiving files.
  • Mismatched request headers: Your screenshot shows specific headers (like User-Agent, Accept, or auth tokens) the API expects. Omitting any of these can lead to the API returning an error page instead of a valid image.
  • Ignoring HTTP status codes: If the API returns a 4xx/5xx status code, you're getting an error response, not an image. Check $httpStatus to confirm the request succeeded.

Corrected Code for Your Use Case

Here's a tailored example that mirrors the request in your screenshot—make sure to copy all headers exactly:

// Step 1: Read your source file
$sourceFile = '/path/to/your/local-image.jpg';
$fileData = file_get_contents($sourceFile);
if (!$fileData) {
    exit("Failed to read source file: $sourceFile");
}

// Step 2: Configure the API request
$apiUrl = 'https://your-api-endpoint-from-screenshot.com';
$ch = curl_init($apiUrl);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileData);
// Copy ALL headers from your screenshot here
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/octet-stream',
    'Accept: */*',
    'User-Agent: Mozilla/5.0 (your-user-agent-from-screenshot)',
    // Add any other headers like Authorization, Host, etc.
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
// Disable SSL verification only for testing (never in production)
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Step 3: Execute and check response
$response = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    exit("cURL Error: " . curl_error($ch));
}
curl_close($ch);

// Step 4: Save the response as an image (binary-safe)
$outputFile = '/path/to/save/result-image.jpg';
if (file_put_contents($outputFile, $response, FILE_BINARY)) {
    echo "Image saved successfully! Check $outputFile";
} else {
    echo "Failed to save the image file";
}

// Debug tip: If the image is still corrupted, open it in a text editor—you might see an HTML error message from the API

Quick Debugging Steps

  1. Match your request headers exactly to the screenshot—even a missing User-Agent can break the API's response.
  2. Check $httpStatus; if it's not 200, print $response to see what error the API is returning.
  3. Open the "corrupted" image in a text editor—if you see HTML/JSON, the API isn't sending a valid image back.

内容的提问来源于stack exchange,提问作者Gustavo Catano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:24:35