Notice
- The URL of the result image is valid for 1 hour. Please download the image file promptly.
- HTTP status 200 means that the http request is successful, not that the background change is successful. Please refer to the status code description for details.
- The minimum resolution of the input image file is 256 x 256, and the maximum resolution is 4096 x 4096,and must be in transparent PNG format.
- The maximum resolution of the output image file is 1024 x 1024
Supported Images
Format | Resolution | File size |
---|---|---|
png | Up to 4096 x 4096 | Up to 15MB |
Get Started
See differences between the 3 API call types
API Call Types | Request | Return | Pros & Cons |
---|---|---|---|
Asynchronous | After sending a request, users do not have to wait for an immediate response from the server. The user can obtain the result via Polling. | Return the result by Polling. |
Pros: High success rate when concurrency is high; high processing success rate when network transmission is slow or unstable. Cons: One more interface call compared to synchronous option. |
Synchronous | Send a request and wait to obtain real-time updates from the server. | Immediately return the result. |
Pros: Easy to integrate. Cons: Lower success rate when concurrency is high or network transmission is slow or unstable as compared to asynchronous option. |
Callback | After sending a request, users do not have to wait for an immediate response from the server. When the task is completed, the server will send a callback notification. | After setting the callback URL, the server sends a notification back to the user. |
Pros: Highest processing success rate. Cons: The user requires a server and corresponding back-end resources. |
Asynchronous API Call Sequence Diagram
Synchronous API Call Sequence Diagram
Callback Notification Sequence Diagram
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/r-background' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'scene_type=105' \
-F 'image_url=YOUR_IMG_URL'
#Curl is not suitable for writing callbacks. You need to use backend languages like Go to write callback functions to receive parameters.
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/r-background');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0,'scene_type' => 105, 'image_url' => new CURLFILE("/path/to/image.png")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
// Record the task ID and store it in the database.
$task_id = $result["data"]["task_id"];
<?php
// Callback code.
// Original JSON data.
$jsonData = '{
"status": 200,
"message": "success",
"data": {
"task_id": "13cc3f64-6753-4a59-a06d-38946bc91144",
"image_1": "13cc3f64-6753-4a59-a06d-38946bc91144.jpg",
"image_2": "13cc3f64-6753-4a59-a06d-38946bc91144.jpg",
"state": 1
}
}';
// if needed,Decode JSON data.
$data = json_decode($jsonData, true);
if ( !isset($data["status"]) || $data["status"] != 200 ) {
// request failed, log the details
var_dump($data);
die("post request failed");
}
if ( $data["data"]["state"] == 1 ) {
// task success Store the image in the database based on the taskId.
var_dump($data["data"]["file"]);
} else if ( $data["data"]["state"] < 0) {
// request failed, log the details
var_dump($data);
} else {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
public static void main(String[] args) throws Exception {
String taskId = createTask();
String result = pollingTaskResult(taskId, 0);
System.out.println(result);
}
private static String createTask() throws Exception {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("scene_type", "105")
.addFormDataPart("image_url", "IMAGE_HTTP_URL")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/r-background")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
int status = jsonObject.optInt("status");
if (status != 200) {
throw new Exception(jsonObject.optString("message"));
}
return jsonObject.getJSONObject("data").optString("task_id");
}
private static String pollingTaskResult(String taskId, int pollingTime) throws Exception {
if (pollingTime >= 120) throw new IllegalStateException("Polling result timeout.");
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request taskRequest = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/r-background/" + taskId)
.addHeader("X-API-KEY", "YOUR_API_KEY")
.get()
.build();
Response taskResponse = okHttpClient.newCall(taskRequest).execute();
JSONObject jsonObject = new JSONObject(taskResponse.body().string());
int state = jsonObject.getJSONObject("data").optInt("state");
if (state < 0) { // Error.
throw new Exception(jsonObject.optString("message"));
}
if (state == 1) { // Success and get result.
return jsonObject.getJSONObject("data").toString();
}
Thread.sleep(1000);
return pollingTaskResult(taskId, ++pollingTime);
}
const request = require("request");
const fs = require("fs");
const path = require('path')
const API_KEY = "YOUR_API_KEY";
(async function main() {
const taskId = await createTask()
const result = await polling(() => getTaskResult(taskId))
console.log(`result: ${JSON.stringify(result, null, 2)}`)
})()
const polling = async (fn, delay = 1 * 1000, timeout = 300 * 1000) => {
if (!fn) {
throw new Error('fn is required')
}
try {
const result = await fn()
return result
} catch (error) {
if (error && 'data' in error) {
throw new Error(JSON.stringify(error, null, 2))
}
if (timeout <= 0) {
throw new Error('timeout')
}
await new Promise((resolve) => {
setTimeout(() => {
resolve()
}, delay)
})
return polling(fn, delay, timeout - delay)
}
}
function createTask() {
return new Promise((resolve, reject) => {
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/r-background",
headers: {
"X-API-KEY": API_KEY,
},
formData: {
image_url: 'IMAGE_HTTP_URL',
scene_type: 105,
},
json: true
},
function (error, response) {
if (response.body.data) {
resolve(response.body.data.task_id)
} else {
reject(response.body)
}
}
);
})
}
function getTaskResult(taskId) {
return new Promise((resolve, reject) => {
request(
{
method: "GET",
url: `https://techsz.aoscdn.com/api/tasks/visual/r-background/${taskId}`,
headers: {
"X-API-KEY": API_KEY,
},
json: true
},
function (error, response) {
if (!response.body.data) reject(response.body)
const { progress, state } = response.body.data
if (state < 0) reject(response.body)
if (progress >= 100) resolve(response.body)
reject(null)
}
);
})
}
import time
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_NETWORK_URL = 'YOUR_IMAGE_NETWORK_URL'
def create_task():
headers = {'X-API-KEY': API_KEY}
data = {'scene_type': 105, 'image_url': IMAGE_NETWORK_URL}
url = 'https://techsz.aoscdn.com/api/tasks/visual/r-background'
# Create a task
response = requests.post(url, headers=headers, data=data)
task_id = None
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
result_tag = 'failed'
if 'data' in response_json:
response_json_data = response_json['data']
if 'task_id' in response_json_data:
result_tag = 'successful'
task_id = response_json_data['task_id']
print(f'Result of created task({result_tag}): {response_json}')
else:
# request failed, log the details
print(f'Error: Failed to create task,{response.text}')
return task_id
# get the task result
# 1、"The polling interval is set to 1 second."
# 2、"The polling time is around 300 seconds."
def polling_task_result(task_id,time_out=300):
headers = {'X-API-KEY': API_KEY}
url = f'https://techsz.aoscdn.com/api/tasks/visual/r-background/{task_id}'
for i in range(time_out):
if i != 0:
time.sleep(1)
response = requests.get(url, headers=headers)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
if 'data' in response_json:
response_json_data = response_json['data']
if 'state' in response_json_data:
task_state = response_json_data['state']
if task_state == 1:
# task success
print(f'Result(successful): {response_json}')
break
elif task_state < 0:
# Task exception, logging the error.
# You can choose to continue the loop with 'continue' or break the loop with 'break'
print(f'Result(failed): {response_json}')
break
print(f'Result(polling): {response_json}')
if i == time_out-1:
# Timeout, log the details, and search for support from the picwish service.
print('Error: Timeout while polling.')
else:
# Task exception, logging the error.
# You can choose to continue the loop with 'continue' or break the loop with 'break'
print(f'Error: Failed to get the task\'s result,{response.text}')
break
def main():
task_id = create_task()
if task_id is None:
print('Error: Failed to create task,task id is None.')
return
polling_task_result(task_id)
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
public static HttpClient client = new HttpClient();
private static string url = "https://techsz.aoscdn.com/api/tasks/visual/r-background";
private static string API_KEY = "YOUR_API_KEY";
private static string imageUrl = "IMAGE_HTTP_URL";
static async Task Main(string[] args)
{
try
{
//Create a task.
var taskId = await CreateTask();
//Retrieve the results by looping thirty times.
var result = await Polling(() => GetTaskResult(taskId), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(300));
Console.WriteLine($"result: {result.ToString()}");
}
catch (Exception ex)
{
//Request from user server failed. Please record the relevant error logs.
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
static async Task<string> CreateTask()
{
var requestUrl = url;
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent("105"), "scene_type");
multipartContent.Add(new StringContent(imageUrl), "image_url");
client.DefaultRequestHeaders.Add("X-API-KEY", API_KEY);
//User server initiates a request.
var response = await client.PostAsync(requestUrl, multipartContent);
var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
if (responseJson["data"] != null)
{
return responseJson["data"]["task_id"].ToString();
}
else
{
//Request from user server failed. Please record the relevant error logs.
throw new Exception(responseJson.ToString());
}
}
static async Task<JObject> GetTaskResult(string taskId)
{
var requestUrl = $"{url}/{taskId}";
var response = await client.GetAsync(requestUrl);
var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
if (responseJson["data"]["image_1"] != null)
{
return responseJson;
}
else
{
//Task processing
throw new Exception(responseJson.ToString());
}
}
//Polling requests using the following methods
//1. The polling interval is set to 1 second,
//2. The polling time does not exceed 300 seconds
static async Task<JObject> Polling(Func<Task<JObject>> fn, TimeSpan delay, TimeSpan timeout)
{
var endTime = DateTime.Now + timeout;
while (DateTime.Now < endTime)
{
try
{
return await fn();
}
catch
{
//You can choose to continue the loop with "continue" or break the loop with "break".
Console.WriteLine("polling...");
////Wait for one second between each loop iteration.
await Task.Delay(delay);
}
}
//Timeout, log the details, and search for support from the picwish service.
throw new Exception("timeout");
}
}
import Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/r-background"
/// Begin task
func start() {
createTask { taskId in
// Task succeed, get result. Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 300 seconds
let startTime = CFAbsoluteTimeGetCurrent()
getTaskResult(taskId: taskId, taskStartTime: startTime) { result in
print(result)
}
}
}
/// Create a task
func createTask(completion: @escaping (String) -> Void) {
let url = URL(string: BASE_URL)!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
AF.upload(multipartFormData: { multipartFormData in
if let imageUrl = "{YOUR_IMAGE_NETWORK_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "image_1.jpg", mimeType: "image/jpeg")
}
if let imageUrl = "{YOUR_IMAGE_NETWORK_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "image_2.jpg", mimeType: "image/jpeg")
}
if let format = "0".data(using: .utf8) {
multipartFormData.append(format, withName: "sync")
}
if let format = "105".data(using: .utf8) {
multipartFormData.append(format, withName: "scene_type")
}
}, to: url, method: .post, headers: headers).responseData { response in
switch response.result {
case .success(let value):
if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let taskId = data["task_id"] as? String {
completion(taskId)
}
case .failure(let error):
print(error)
}
}
}
/// Get result
func getTaskResult(taskId: String,
taskStartTime: CFAbsoluteTime,
completion: @escaping ([String: Any]) -> Void) {
let url = URL(string: "\(BASE_URL)/\(taskId)")!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
AF.request(url, method: .get, headers: headers).responseData { response in
switch response.result {
case .success(let value):
print(response.debugDescription)
guard let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let state = data["state"] as? Int else {
print("parse failed")
return
}
// Task failed, log the details, and exit the loop
if state < 0 {
return
}
// Task successful
if state == 1 {
completion(["data": data])
return
}
// Retrieve the results by looping only 300 times
let endTime = CFAbsoluteTimeGetCurrent()
if endTime - taskStartTime < 300 {
// Wait for one second between each loop iteration
sleep(1)
getTaskResult(taskId: taskId, taskStartTime: taskStartTime, completion: completion)
return
}
// Timeout, log the details, and search for support from the picwish service
print("timeout")
case .failure(let error):
// Request from user server failed. Please record the relevant error logs
print(error)
}
}
}
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"time"
)
const (
APIKey = "YOUR_API_KEY"
BaseURL = "https://techsz.aoscdn.com/api/tasks/visual/r-background"
)
// taskResponse
type taskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
type BackgroundTaskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Progress uint `json:"progress"`
State int `json:"state"`
Image1 string `json:"image_1"`
Image2 string `json:"image_2"`
Image3 string `json:"image_3"`
Image4 string `json:"image_4"`
} `json:"data"`
}
func createTask() (string, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
_ = writer.WriteField("scene_type", "105")
err := writer.Close()
if err != nil {
fmt.Println("Close error", err)
return "", err
}
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", BaseURL, body)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("X-API-KEY", APIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var taskResp *taskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return "", err
}
if taskResp.Status != 200 {
// Request from user server failed. Please record the relevant error logs.
var taskError error
taskError = errors.New("error task id")
return "", taskError
}
return taskResp.Data.TaskId, nil
}
func getTaskResult(taskId string) (*BackgroundTaskResponse, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", BaseURL, taskId), nil)
if err != nil {
return nil, err
}
req.Header.Set("X-API-KEY", APIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
// failed. Please record the relevant error logs.
return nil, err
}
var taskResp *BackgroundTaskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return nil, err
}
return taskResp, err
}
func main() {
taskId, err := createTask()
if err != nil {
fmt.Println("Error creating task:", err)
return
}
//Retrieve the results by looping 300 times.
for i := 0; i < 300; i++ {
if i != 0 {
time.Sleep(time.Second) // Wait for one second between each loop iteration.
}
result, err := getTaskResult(taskId)
if err != nil {
fmt.Println("Error getting task result:", err, taskId)
break
}
if result.Status != 200 {
// Request from user server failed. Please record the relevant error logs.
var taskError error
taskError = errors.New("error get task id")
fmt.Println("result error ", result, taskError, taskId)
//You can choose to continue polling or break, both options are acceptable.
continue
} else {
if result.Data.State == 1 {
//Complete the task and end the polling.
fmt.Println("result", result)
break
} else if result.Data.State < 0 {
// Task failed, log the details, and exit the loop.
fmt.Println("result", result)
break
}
// Other tasks in the 'state' are in progress, continue polling.
if i == 299 {
// Timeout, log the details, and search for support from the Zuo Tang customer service.
fmt.Println("result", result, taskId)
}
}
}
}
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/r-background' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'scene_type=105' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'image_url=YOUR_IMG_URL'
#Curl is not suitable for writing callbacks. You need to use backend languages like Go to write callback functions to receive parameters.
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/r-background');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0,'scene_type' => 105, 'callback_url' => "YOUR_URL", 'image_url' => "YOUR_IMG_URL"));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
// Record the task ID and store it in the database.
$task_id = $result["data"]["task_id"];
<?php
// Callback code.
// Original JSON data.
$jsonData = '{
"status": 200,
"message": "success",
"data": {
"task_id": "13cc3f64-6753-4a59-a06d-38946bc91144",
"image_1": "13cc3f64-6753-4a59-a06d-38946bc91144.jpg",
"image_2": "13cc3f64-6753-4a59-a06d-38946bc91144.jpg",
"state": 1
}
}';
// if needed,Decode JSON data.
$data = json_decode($jsonData, true);
if ( !isset($data["status"]) || $data["status"] != 200 ) {
// request failed, log the details
var_dump($data);
die("post request failed");
}
if ( $data["data"]["state"] == 1 ) {
// task success Store the image in the database based on the taskId.
var_dump($data["data"]["file"]);
} else if ( $data["data"]["state"] < 0) {
// request failed, log the details
var_dump($data);
} else {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("scene_type", "105")
.addFormDataPart("image_url", "IMAGE_HTTP_URL")
.addFormDataPart("callback_url", "YOUR_SERVER_URL")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/r-background")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
System.out.println("Response json string: " + response.body().string());
const request = require("request");
const fs = require("fs");
const path = require('path')
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/r-background",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
callback_url: "YOUR_SERVER_URL",
scene_type: 105,
image_url: "IMAGE_HTTP_URL",
},
json: true
},
function (error, response) {
if (response.body.data) {
console.log(response.body.data)
}
throw new Error(JSON.stringify(response.body, null, 2))
}
);
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_NETWORK_URL = 'YOUR_IMAGE_NETWORK_URL'
SERVER_URL = 'YOUR_SERVER_URL'
def main():
headers = {'X-API-KEY': API_KEY}
data = {'callback_url': SERVER_URL, 'scene_type': 105, 'image_url': IMAGE_NETWORK_URL}
url = 'https://techsz.aoscdn.com/api/tasks/visual/r-background'
response = requests.post(url, headers=headers, data=data)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
# Task successful. Recorded in the database with task ID.
print(f'Result(successful): {response_json}')
else:
# Request from user server failed. Please record the relevant error logs.
print(f'Error: Failed to get the result,{response.text}')
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
string apiKey = "YOUR_API_KEY";
string url = "https://techsz.aoscdn.com/api/tasks/visual/r-background";
string imageUrl = "IMAGE_HTTP_URL";
string callbackUrl = "YOUR_SERVER_URL";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent("105"), "scene_type");
content.Add(new StringContent(imageUrl), "image_url");
content.Add(new StringContent(callbackUrl), "callback_url");
//User server initiates a request.
var response = await client.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
//Task successful.
var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
Console.WriteLine($"result: {responseContent}");
}
else
{
//Task processing, abnormal situation, seeking assistance from customer service of picwish
Console.WriteLine($"Error: {responseContent}");
}
}
}
Console.ReadKey();
}
}
import Alamofire
import Foundation
let API_KEY = "YOUR_API_KEY"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/r-background"
func createTask(completion: @escaping (String) -> Void) {
let url = URL(string: BASE_URL)!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
AF.upload(multipartFormData: { multipartFormData in
if let imageUrl = "{YOUR_IMAGE_NETWORK_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "image_1.jpg", mimeType: "image/jpeg")
}
if let imageUrl = "{YOUR_IMAGE_NETWORK_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "image_2.jpg", mimeType: "image/jpeg")
}
if let data = "YOUR_SERVER_URL".data(using: .utf8) {
multipartFormData.append(data, withName: "callback_url")
}
if let format = "0".data(using: .utf8) {
multipartFormData.append(format, withName: "sync")
}
if let format = "105".data(using: .utf8) {
multipartFormData.append(format, withName: "scene_type")
}
}, to: url, method: .post, headers: headers).responseData { response in
switch response.result {
case .success(let value):
if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let taskId = data["task_id"] as? String {
completion(taskId)
}
case .failure(let error):
print(error)
}
}
}
// File 1: User server initiates a request.
package api
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"testing"
)
type TaskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
func TestBackgroundTechApi(t *testing.T) {
url := "https://techsz.aoscdn.com/api/tasks/visual/r-background"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
_ = writer.WriteField("scene_type", "105")
err := writer.Close()
if err != nil {
fmt.Println("Close error", err)
return
}
client := &http.Client{}
req, err := http.NewRequest("POST", url, payload)
if err != nil {
fmt.Println("Close error", err)
return
}
req.Header.Add("X-API-KEY", "YOUR_API_KEY")
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println("client query error", err)
return
}
defer res.Body.Close()
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Read body error", err)
return
}
var taskResp *TaskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
if taskResp.Status != http.StatusOK {
// Request from user server failed. Please record the relevant error logs.
fmt.Println("failed to get the result", taskResp)
} else {
//Task successful. Recorded in the database with task ID.
fmt.Println("result Successfully", taskResp)
}
}
// picwish server initiates a request to the user server, and the interface of the user server receives the parameters.
package main
import (
"encoding/json"
"fmt"
)
type BackgroundTaskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Progress uint `json:"progress"`
State int `json:"state"`
Image1 string `json:"image_1"`
Image2 string `json:"image_2"`
Image3 string `json:"image_3"`
Image4 string `json:"image_4"`
} `json:"data"`
}
func main() {
// JSON data is passed and received here, and code modification is required.
jsonData := `{
"status": 200,
"message": "Success",
"data": {
"task_id": "123456",
"file": "file_data",
"State": 1,
"image_1": "image_1",
"image_2": "image_2",
}
}`
// Parse JSON data into BackgroundTaskResponse struct
var response BackgroundTaskResponse
err := json.Unmarshal([]byte(jsonData), &response)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
// Query the relevant content in the database based on the taskID and associate it with the image below.
fmt.Println("Image:", response.Data.TaskId)
// Print the 'image' field
fmt.Println("Image1:", response.Data.Image1)
fmt.Println("Image2:", response.Data.Image2)
}
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/r-background' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'scene_type=105' \
-F 'image_file=@/path/to/image.png'
#Get the cutout result
#Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 300 seconds
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/r-background/{task_id}' \
-H 'X-API-KEY: YOUR_API_KEY' \
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/r-background');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data"
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0,'scene_type' => 105, 'image_file' => new CURLFILE("/path/to/image.png")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
// var_dump($result);
$task_id = $result["data"]["task_id"];
//get the task result
// 1、"The polling interval is set to 1 second."
//2 "The polling time is around 300 seconds."
for ($i = 1; $i <= 300; $i++) {
if ($i != 1) {
sleep(1);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://techsz.aoscdn.com/api/tasks/visual/r-background/".$task_id);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
var_dump($result);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// Task exception, logging the error.
//You can choose to continue the loop with 'continue' or break the loop with 'break'
var_dump($result);
continue;
}
if ( $result["data"]["state"] == 1 ) {
// task success
var_dump($result["data"]["file"]);
break;
} else if ( $result["data"]["state"] < 0) {
// request failed, log the details
var_dump($result);
break;
} else {
// Task processing
if ($i == 300) {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
}
}
public static void main(String[] args) throws Exception {
String taskId = createTask();
String result = pollingTaskResult(taskId, 0);
System.out.println(result);
}
private static String createTask() throws Exception {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("scene_type", "105")
.addFormDataPart("image_file", {IMAGE_FILE_NAME}, RequestBody.create({IMAGE_FILE}, MediaType.parse("image/jpeg")))
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/r-background")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
int status = jsonObject.optInt("status");
if (status != 200) {
throw new Exception(jsonObject.optString("message"));
}
return jsonObject.getJSONObject("data").optString("task_id");
}
private static String pollingTaskResult(String taskId, int pollingTime) throws Exception {
if (pollingTime >= 120) throw new IllegalStateException("Polling result timeout.");
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request taskRequest = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/r-background/" + taskId)
.addHeader("X-API-KEY", "YOUR_API_KEY")
.get()
.build();
Response taskResponse = okHttpClient.newCall(taskRequest).execute();
JSONObject jsonObject = new JSONObject(taskResponse.body().string());
int state = jsonObject.getJSONObject("data").optInt("state");
if (state < 0) { // Error.
throw new Exception(jsonObject.optString("message"));
}
if (state == 1) { // Success and get result.
return jsonObject.getJSONObject("data").toString();
}
Thread.sleep(1000);
return pollingTaskResult(taskId, ++pollingTime);
}
const request = require("request");
const fs = require("fs");
const path = require('path')
const API_KEY = "YOUR_API_KEY";
(async function main() {
const taskId = await createTask()
const result = await polling(() => getTaskResult(taskId))
console.log(`result: ${JSON.stringify(result, null, 2)}`)
})()
const polling = async (fn, delay = 1 * 1000, timeout = 300 * 1000) => {
if (!fn) {
throw new Error('fn is required')
}
try {
const result = await fn()
return result
} catch (error) {
if (error && 'data' in error) {
throw new Error(JSON.stringify(error, null, 2))
}
if (timeout <= 0) {
throw new Error('timeout')
}
await new Promise((resolve) => {
setTimeout(() => {
resolve()
}, delay)
})
return polling(fn, delay, timeout - delay)
}
}
function createTask() {
return new Promise((resolve, reject) => {
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/r-background",
headers: {
"X-API-KEY": API_KEY,
},
formData: {
image_file: fs.createReadStream(path.join(__dirname, './test.png')),
scene_type: 105,
},
json: true
},
function (error, response) {
if (response.body.data) {
resolve(response.body.data.task_id)
} else {
reject(response.body)
}
}
);
})
}
function getTaskResult(taskId) {
return new Promise((resolve, reject) => {
request(
{
method: "GET",
url: `https://techsz.aoscdn.com/api/tasks/visual/r-background/${taskId}`,
headers: {
"X-API-KEY": API_KEY,
},
json: true
},
function (error, response) {
if (!response.body.data) reject(response.body)
const { progress, state } = response.body.data
if (state < 0) reject(response.body)
if (progress >= 100) resolve(response.body)
reject(null)
}
);
})
}
import os
import time
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_FILE_PATH = 'YOUR_IMAGE_FILE_PATH'
def create_task():
assert os.path.exists(IMAGE_FILE_PATH), f'Error: File({IMAGE_FILE_PATH}) does not exist.'
headers = {'X-API-KEY': API_KEY}
data = {'scene_type': 105}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/visual/r-background'
# Create a task
response = requests.post(url, headers=headers, data=data, files=files)
task_id = None
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
result_tag = 'failed'
if 'data' in response_json:
response_json_data = response_json['data']
if 'task_id' in response_json_data:
result_tag = 'successful'
task_id = response_json_data['task_id']
print(f'Result of created task({result_tag}): {response_json}')
else:
# request failed, log the details
print(f'Error: Failed to create task,{response.text}')
return task_id
# get the task result
# 1、"The polling interval is set to 1 second."
# 2、"The polling time is around 300 seconds."
def polling_task_result(task_id,time_out=300):
headers = {'X-API-KEY': API_KEY}
url = f'https://techsz.aoscdn.com/api/tasks/visual/r-background/{task_id}'
for i in range(time_out):
if i != 0:
time.sleep(1)
response = requests.get(url, headers=headers)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
if 'data' in response_json:
response_json_data = response_json['data']
if 'state' in response_json_data:
task_state = response_json_data['state']
if task_state == 1:
# task success
print(f'Result(successful): {response_json}')
break
elif task_state < 0:
# Task exception, logging the error.
# You can choose to continue the loop with 'continue' or break the loop with 'break'
print(f'Result(failed): {response_json}')
break
print(f'Result(polling): {response_json}')
if i == time_out-1:
# Timeout, log the details, and search for support from the picwish service.
print('Error: Timeout while polling.')
else:
# Task exception, logging the error.
# You can choose to continue the loop with 'continue' or break the loop with 'break'
print(f'Error: Failed to get the task\'s result,{response.text}')
break
def main():
task_id = create_task()
if task_id is None:
print('Error: Failed to create task,task id is None.')
return
polling_task_result(task_id)
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
public static HttpClient client = new HttpClient();
private static string url = "https://techsz.aoscdn.com/api/tasks/visual/r-background";
private static string API_KEY = "YOUR_API_KEY";
private static string imagePath = "test.png";
static async Task Main(string[] args)
{
try
{
//Create a task.
var taskId = await CreateTask();
//Retrieve the results by looping thirty times.
var result = await Polling(() => GetTaskResult(taskId), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(300));
Console.WriteLine($"result: {result.ToString()}");
}
catch (Exception ex)
{
//Request from user server failed. Please record the relevant error logs.
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
static async Task<string> CreateTask()
{
var requestUrl = url;
var multipartContent = new MultipartFormDataContent();
var fileStream = File.OpenRead(imagePath);
multipartContent.Add(new StreamContent(fileStream), "image_file", Path.GetFileName(imagePath));
multipartContent.Add(new StringContent("105"), "scene_type");
client.DefaultRequestHeaders.Add("X-API-KEY", API_KEY);
//User server initiates a request.
var response = await client.PostAsync(requestUrl, multipartContent);
var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
if (responseJson["data"] != null)
{
return responseJson["data"]["task_id"].ToString();
}
else
{
//Request from user server failed. Please record the relevant error logs.
throw new Exception(responseJson.ToString());
}
}
static async Task<JObject> GetTaskResult(string taskId)
{
var requestUrl = $"{url}/{taskId}";
var response = await client.GetAsync(requestUrl);
var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
if (responseJson["data"]["image_1"] != null)
{
return responseJson;
}
else
{
//Task processing
throw new Exception(responseJson.ToString());
}
}
//Polling requests using the following methods
//1. The polling interval is set to 1 second,
//2. The polling time does not exceed 300 seconds
static async Task<JObject> Polling(Func<Task<JObject>> fn, TimeSpan delay, TimeSpan timeout)
{
var endTime = DateTime.Now + timeout;
while (DateTime.Now < endTime)
{
try
{
return await fn();
}
catch
{
//You can choose to continue the loop with "continue" or break the loop with "break".
Console.WriteLine("polling...");
//Wait for one second between each loop iteration.
await Task.Delay(delay);
}
}
//Timeout, log the details, and search for support from the picwish service.
throw new Exception("timeout");
}
}
import Alamofire
import Foundation
let API_KEY = "YOUR_API_KEY"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/r-background"
/// Begin task
func start() {
createTask { taskId in
// Task succeed, get result. Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 300 seconds
let startTime = CFAbsoluteTimeGetCurrent()
getTaskResult(taskId: taskId, taskStartTime: startTime) { result in
print(result)
}
}
}
/// Create a task
func createTask(completion: @escaping (String) -> Void) {
let url = URL(string: BASE_URL)!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
let imagePath1 = Bundle.main.path(forResource: "image_1", ofType: "jpg")!
let imagePath2 = Bundle.main.path(forResource: "image_2", ofType: "jpg")!
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(URL(fileURLWithPath: imagePath1), withName: "image_file", fileName: "image_1.jpg", mimeType: "image/jpeg")
multipartFormData.append(URL(fileURLWithPath: imagePath2), withName: "image_file", fileName: "image_2.jpg", mimeType: "image/jpeg")
if let format = "0".data(using: .utf8) {
multipartFormData.append(format, withName: "sync")
}
if let format = "105".data(using: .utf8) {
multipartFormData.append(format, withName: "scene_type")
}
}, to: url, method: .post, headers: headers).responseData { response in
switch response.result {
case .success(let value):
if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let taskId = data["task_id"] as? String {
completion(taskId)
}
case .failure(let error):
print(error)
}
}
}
/// Get result
func getTaskResult(taskId: String,
taskStartTime: CFAbsoluteTime,
completion: @escaping ([String: Any]) -> Void) {
let url = URL(string: "\(BASE_URL)/\(taskId)")!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
AF.request(url, method: .get, headers: headers).responseData { response in
switch response.result {
case .success(let value):
print(response.debugDescription)
guard let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let state = data["state"] as? Int else {
print("parse failed")
return
}
// Task failed, log the details, and exit the loop
if state < 0 {
return
}
// Task successful
if state == 1 {
completion(["data": data])
return
}
// Retrieve the results by looping only 300 times
let endTime = CFAbsoluteTimeGetCurrent()
if endTime - taskStartTime < 300 {
// Wait for one second between each loop iteration
sleep(1)
getTaskResult(taskId: taskId, taskStartTime: taskStartTime, completion: completion)
return
}
// Timeout, log the details, and search for support from the picwish service
print("timeout")
case .failure(let error):
// Request from user server failed. Please record the relevant error logs
print(error)
}
}
}
// File 1: User server initiates a request.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type TaskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
func main() {
apiKey := "YOUR_API_KEY"
url := "https://techsz.aoscdn.com/api/tasks/visual/r-background"
imagePath := "test.png"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
_ = writer.WriteField("scene_type", "105")
file, err := os.Open(imagePath)
if err != nil {
fmt.Println("Error: ", err)
return
}
defer file.Close()
part, err := writer.CreateFormFile("image_file", filepath.Base(imagePath))
if err != nil {
fmt.Println("Error: ", err)
return
}
io.Copy(part, file)
writer.Close()
req, err := http.NewRequest("POST", url, body)
if err != nil {
fmt.Println("Error: ", err)
return
}
req.Header.Set("X-API-KEY", apiKey)
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error: ", err)
return
}
defer res.Body.Close()
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Error: ", err)
return
}
var taskResp TaskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
if taskResp.Status != http.StatusOK {
// Request from user server failed. Please record the relevant error logs.
fmt.Println("failed to get the result", taskResp)
} else {
//Task successful. Recorded in the database with task ID.
fmt.Println("failed to get the result", taskResp)
}
}
// picwish server initiates a request to the user server, and the interface of the user server receives the parameters.
package main
import (
"encoding/json"
"fmt"
)
type BackgroundTaskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Progress uint `json:"progress"`
State int `json:"state"`
Image1 string `json:"image_1"`
Image2 string `json:"image_2"`
Image3 string `json:"image_3"`
Image4 string `json:"image_4"`
} `json:"data"`
}
func main() {
// JSON data is passed and received here, and code modification is required.
jsonData := `{
"status": 200,
"message": "Success",
"data": {
"task_id": "123456",
"State": 1,
"image_1": "image_1",
"image_2": "image_2",
}
}`
// Parse JSON data into BackgroundTaskResponse struct
var response BackgroundTaskResponse
err := json.Unmarshal([]byte(jsonData), &response)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
// Query the relevant content in the database based on the taskID and associate it with the image below.
fmt.Println("Image:", response.Data.TaskId)
// Print the 'image' field
fmt.Println("Image1:", response.Data.Image1)
fmt.Println("Image2:", response.Data.Image2)
}
#Create a task
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/r-background' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'scene_type=105' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'image_file=@/path/to/image.png'
#Get the cutout result
#Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 300 seconds
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/r-background/{task_id}' \
-H 'X-API-KEY: YOUR_API_KEY' \
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/r-background');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0,'scene_type' => 105, 'callback_url' => "YOUR_URL", 'image_file' => new CURLFILE("/path/to/image.png")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
// var_dump($result);
$task_id = $result["data"]["task_id"];
//get the task result
// 1、"The polling interval is set to 1 second."
//2 "The polling time is around 300 seconds."
for ($i = 1; $i <= 300; $i++) {
if ($i != 1) {
sleep(1);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://techsz.aoscdn.com/api/tasks/visual/r-background/".$task_id);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
var_dump($result);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// Task exception, logging the error.
//You can choose to continue the loop with 'continue' or break the loop with 'break'
var_dump($result);
continue;
}
if ( $result["data"]["state"] == 1 ) {
// task success
var_dump($result["data"]["image_1"]);
var_dump($result["data"]["image_2"]);
break;
} else if ( $result["data"]["state"] < 0) {
// request failed, log the details
var_dump($result);
break;
} else {
// Task processing
if ($i == 300) {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
}
}
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("scene_type", "105")
.addFormDataPart("image_file", {IMAGE_FILE_NAME}, RequestBody.create({IMAGE_FILE}, MediaType.parse("image/jpeg")))
.addFormDataPart("callback_url", "YOUR_SERVER_URL")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/r-background")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
System.out.println("Response json string: " + response.body().string());
const request = require("request");
const fs = require("fs");
const path = require('path')
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/r-background",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
callback_url: "YOUR_SERVER_URL",
scene_type: 105,
image_file: fs.createReadStream(path.join(__dirname, './test.png')),
},
json: true
},
function (error, response) {
if (response.body.data) {
console.log(response.body.data)
}
throw new Error(JSON.stringify(response.body, null, 2))
}
);
import os
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_FILE_PATH = 'YOUR_IMAGE_FILE_PATH'
SERVER_URL = 'YOUR_SERVER_URL'
def main():
assert os.path.exists(IMAGE_FILE_PATH), f'Error: File({IMAGE_FILE_PATH}) does not exist.'
headers = {'X-API-KEY': API_KEY}
data = {'callback_url': SERVER_URL, 'scene_type': 105}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/visual/r-background'
# Create a task
response = requests.post(url, headers=headers, data=data, files=files)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
# Task successful. Recorded in the database with task ID.
print(f'Result(successful): {response_json}')
else:
# Request from user server failed. Please record the relevant error logs.
print(f'Error: Failed to get the result,{response.text}')
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
string apiKey = "YOUR_API_KEY";
string url = "https://techsz.aoscdn.com/api/tasks/visual/r-background";
string imagePath = "test.jpg";
string callbackUrl = "YOUR_SERVER_URL";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
using (var content = new MultipartFormDataContent())
{
var imageContent = new StreamContent(File.OpenRead(imagePath));
imageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
content.Add(new StringContent(callbackUrl), "callback_url");
content.Add(imageContent, "image_file", Path.GetFileName(imagePath));
content.Add(new StringContent("105"), "scene_type");
//User server initiates a request.
var response = await client.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
//Task successful.
var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
Console.WriteLine($"result: {responseContent}");
}
else
{
//Task processing, abnormal situation, seeking assistance from customer service of picwish
Console.WriteLine($"Error: {responseContent}");
}
}
}
Console.ReadKey();
}
}
import Alamofire
import Foundation
let API_KEY = "YOUR_API_KEY"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/r-background"
/// Create a task
func createTask(completion: @escaping (String) -> Void) {
let url = URL(string: BASE_URL)!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
let imagePath1 = Bundle.main.path(forResource: "image_1", ofType: "jpg")!
let imagePath2 = Bundle.main.path(forResource: "image_2", ofType: "jpg")!
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(URL(fileURLWithPath: imagePath1), withName: "image_file", fileName: "image_1.jpg", mimeType: "image/jpeg")
multipartFormData.append(URL(fileURLWithPath: imagePath2), withName: "image_file", fileName: "image_2.jpg", mimeType: "image/jpeg")
if let data = "YOUR_SERVER_URL".data(using: .utf8) {
multipartFormData.append(data, withName: "callback_url")
}
if let format = "0".data(using: .utf8) {
multipartFormData.append(format, withName: "sync")
}
if let format = "105".data(using: .utf8) {
multipartFormData.append(format, withName: "scene_type")
}
}, to: url, method: .post, headers: headers).responseData { response in
switch response.result {
case .success(let value):
if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let taskId = data["task_id"] as? String {
completion(taskId)
}
case .failure(let error):
print(error)
}
}
}
package main
import (
"bytes"
"encoding/json"
_ "encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
const (
APIKey = "YOUR_API_KEY"
BaseURL = "https://techsz.aoscdn.com/api/tasks/visual/r-background"
)
// taskResponse
type taskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
type BackgroundTaskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Progress uint `json:"progress"`
State int `json:"state"`
Image1 string `json:"image_1"`
Image2 string `json:"image_2"`
Image3 string `json:"image_3"`
Image4 string `json:"image_4"`
} `json:"data"`
}
func createTask() (string, error) {
file, err := os.Open("test.png")
if err != nil {
return "", err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("image_file", filepath.Base("test.png"))
_ = writer.WriteField("scene_type", "105")
_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
if err != nil {
return "", err
}
_, err = io.Copy(part, file)
err = writer.Close()
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", BaseURL, body)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("X-API-KEY", APIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var taskResp *taskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return "", err
}
if err != nil {
return "", err
}
if taskResp.Status != 200 {
// Request from user server failed. Please record the relevant error logs.
var taskError error
taskError = errors.New("error task id")
return "", taskError
}
return taskResp.Data.TaskId, nil
}
func getTaskResult(taskId string) (*BackgroundTaskResponse, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", BaseURL, taskId), nil)
if err != nil {
return nil, err
}
req.Header.Set("X-API-KEY", APIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
// failed. Please record the relevant error logs.
return nil, err
}
var taskResp *BackgroundTaskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return nil, err
}
if err != nil {
return nil, err
}
return taskResp, err
}
func main() {
taskId, err := createTask()
if err != nil {
fmt.Println("Error creating task:", err)
return
}
//Retrieve the results by looping 300 times.
for i := 0; i < 300; i++ {
if i != 0 {
time.Sleep(time.Second) // Wait for one second between each loop iteration.
}
result, err := getTaskResult(taskId)
if err != nil {
fmt.Println("Error getting task result:", err, taskId)
break
}
if result.Status != 200 {
// Request from user server failed. Please record the relevant error logs.
var taskError error
taskError = errors.New("error get task id")
fmt.Println("result error ", result, taskError, taskId)
//You can choose to continue polling or break, both options are acceptable.
continue
} else {
if result.Data.State == 1 {
//Complete the task and end the polling.
fmt.Println("result", result)
break
} else if result.Data.State < 0 {
// Task failed, log the details, and exit the loop.
fmt.Println("result", result)
break
}
// Other tasks in the 'state' are in progress, continue polling.
if i == 299 {
// Timeout, log the details, and search for support from the Zuo Tang customer service.
fmt.Println("result", result, taskId)
}
}
}
}