Skip to content

Commit d500c06

Browse files
authored
Merge pull request #180 from jpush/feature/20201214_image_api
新增图片操作接口
2 parents 115e2b1 + 4ba7272 commit d500c06

File tree

13 files changed

+827
-17
lines changed

13 files changed

+827
-17
lines changed

README.md

+28
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,34 @@ try {
358358
}
359359
```
360360

361+
### Image Client 样例
362+
363+
> 以下片断来自项目代码里面的文件:example / cn.jpush.api.examples.ImageExample
364+
* 支持通过URL或者文件来上传图片
365+
```Java
366+
public static void testUploadImageByUrl() throws APIConnectionException, APIRequestException {
367+
ImageClient client = new ImageClient(MASTER_SECRET, APP_KEY);
368+
ImageUrlPayload payload = ImageUrlPayload.newBuilder()
369+
.setImageType(ImageType.LARGE_ICON)
370+
.setImageUrl("http://xxx.com/image/a.jpg")
371+
.build();
372+
ImageUploadResult imageUploadResult = client.uploadImage(payload);
373+
String mediaId = imageUploadResult.getMediaId();
374+
}
375+
376+
public static void testUploadImageByFile() {
377+
ImageClient client = new ImageClient(MASTER_SECRET, APP_KEY);
378+
ImageFilePayload payload = ImageFilePayload.newBuilder()
379+
.setImageType(ImageType.BIG_PICTURE)
380+
// 本地文件路径
381+
.setOppoFileName("/MyDir/a.jpg")
382+
.setXiaomiFileName("/MyDir/a.jpg")
383+
.build();
384+
ImageUploadResult imageUploadResult = client.uploadImage(payload);
385+
String mediaId = imageUploadResult.getMediaId();
386+
}
387+
```
388+
361389
### Weblogic 使用Java SDK
362390

363391
Weblogic在使用jpush-api-java-client时需要注意的一些事项。
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package cn.jpush.api.image;
2+
3+
import cn.jiguang.common.resp.APIConnectionException;
4+
import cn.jiguang.common.resp.APIRequestException;
5+
import cn.jpush.api.image.model.ImageFilePayload;
6+
import cn.jpush.api.image.model.ImageType;
7+
import cn.jpush.api.image.model.ImageUploadResult;
8+
import cn.jpush.api.image.model.ImageUrlPayload;
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
11+
12+
public class ImageExample {
13+
protected static final Logger LOG = LoggerFactory.getLogger(ImageExample.class);
14+
15+
// demo App defined in resources/jpush-api.conf
16+
protected static final String APP_KEY = "e4ceeaf7a53ad745dd4728f2";
17+
protected static final String MASTER_SECRET = "1582b986adeaf48ceec1e354";
18+
protected static final String GROUP_PUSH_KEY = "2c88a01e073a0fe4fc7b167c";
19+
protected static final String GROUP_MASTER_SECRET = "b11314807507e2bcfdeebe2e";
20+
21+
public static final String TITLE = "Test from API example";
22+
public static final String ALERT = "Test from API Example - alert";
23+
public static final String MSG_CONTENT = "Test from API Example - msgContent";
24+
public static final String REGISTRATION_ID = "0900e8d85ef";
25+
public static final String TAG = "tag_api";
26+
public static long sendCount = 0;
27+
private static long sendTotalTime = 0;
28+
29+
public static void main(String[] args) throws APIConnectionException, APIRequestException {
30+
testUploadImageByFile();
31+
testUploadImageByUrl();
32+
}
33+
34+
public static void testUploadImageByUrl() throws APIConnectionException, APIRequestException {
35+
ImageClient client = new ImageClient(MASTER_SECRET, APP_KEY);
36+
ImageUrlPayload payload = ImageUrlPayload.newBuilder()
37+
.setImageType(ImageType.LARGE_ICON)
38+
.setImageUrl("http://xxx.com/image/a.jpg")
39+
.build();
40+
ImageUploadResult imageUploadResult = client.uploadImage(payload);
41+
String mediaId = imageUploadResult.getMediaId();
42+
}
43+
44+
public static void testUploadImageByFile() {
45+
ImageClient client = new ImageClient(MASTER_SECRET, APP_KEY);
46+
ImageFilePayload payload = ImageFilePayload.newBuilder()
47+
.setImageType(ImageType.BIG_PICTURE)
48+
// 本地文件路径
49+
.setOppoFileName("/MyDir/a.jpg")
50+
.setXiaomiFileName("/MyDir/a.jpg")
51+
.build();
52+
ImageUploadResult imageUploadResult = client.uploadImage(payload);
53+
String mediaId = imageUploadResult.getMediaId();
54+
}
55+
}
56+

pom.xml

+14-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
<groupId>cn.jpush.api</groupId>
55
<artifactId>jpush-client</artifactId>
6-
<version>3.4.7</version>
6+
<version>3.4.8</version>
77
<packaging>jar</packaging>
88
<url>https://github.com/jpush/jpush-api-java-client</url>
99
<name>JPush API Java Client</name>
@@ -51,7 +51,7 @@
5151
<dependency>
5252
<groupId>cn.jpush.api</groupId>
5353
<artifactId>jiguang-common</artifactId>
54-
<version>1.1.9</version>
54+
<version>1.1.10</version>
5555
</dependency>
5656
<dependency>
5757
<groupId>org.apache.httpcomponents</groupId>
@@ -117,6 +117,18 @@
117117
<version>2.0.0</version>
118118
<scope>test</scope>
119119
</dependency>
120+
<dependency>
121+
<groupId>org.mockito</groupId>
122+
<artifactId>mockito-core</artifactId>
123+
<version>1.10.19</version>
124+
<scope>test</scope>
125+
</dependency>
126+
<dependency>
127+
<groupId>org.hamcrest</groupId>
128+
<artifactId>hamcrest-core</artifactId>
129+
<version>2.2</version>
130+
<scope>test</scope>
131+
</dependency>
120132
</dependencies>
121133

122134
<build>
@@ -294,7 +306,6 @@
294306

295307
</plugins>
296308
</build>
297-
298309
<distributionManagement>
299310
<snapshotRepository>
300311
<id>ossrh</id>

src/main/java/cn/jpush/api/file/FileClient.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ public FileUploadResult uploadFile(FileType type, String filename)
5656
String url = _baseUrl + _filesPath + "/" + typeStr;
5757
Map<String, String> fileMap = new HashMap<>();
5858
fileMap.put("filename", filename);
59-
String response = client.formUpload(url, null, fileMap, null);
59+
String response = client.formUploadByPost(url, null, fileMap, null);
6060
LOG.info("uploadFile:{}", response);
6161
return _gson.fromJson(response,
6262
new TypeToken<FileUploadResult>() {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
package cn.jpush.api.image;
2+
3+
import cn.jiguang.common.ClientConfig;
4+
import cn.jiguang.common.ServiceHelper;
5+
import cn.jiguang.common.connection.HttpProxy;
6+
import cn.jiguang.common.connection.IHttpClient;
7+
import cn.jiguang.common.connection.NativeHttpClient;
8+
import cn.jiguang.common.resp.APIConnectionException;
9+
import cn.jiguang.common.resp.APIRequestException;
10+
import cn.jiguang.common.resp.ResponseWrapper;
11+
import cn.jiguang.common.utils.Preconditions;
12+
import cn.jiguang.common.utils.StringUtils;
13+
import cn.jpush.api.image.model.ImageFilePayload;
14+
import cn.jpush.api.image.model.ImageSource;
15+
import cn.jpush.api.image.model.ImageUploadResult;
16+
import cn.jpush.api.image.model.ImageUrlPayload;
17+
import com.google.gson.Gson;
18+
import com.google.gson.JsonElement;
19+
import com.google.gson.JsonSyntaxException;
20+
import org.slf4j.Logger;
21+
import org.slf4j.LoggerFactory;
22+
23+
import java.util.HashMap;
24+
import java.util.Map;
25+
26+
/**
27+
* Provide the ability to upload images to the Jiguang server. Only images in JPG, JPEG and PNG format are supported.
28+
*
29+
* @author fuyx
30+
* @version 2020-12-14
31+
*/
32+
public class ImageClient {
33+
34+
protected static final Logger LOG = LoggerFactory.getLogger(ImageClient.class);
35+
36+
private IHttpClient _httpClient;
37+
private String _baseUrl;
38+
private String _imagesPath;
39+
private Gson _gson = new Gson();
40+
41+
public ImageClient(String masterSecret, String appKey) {
42+
this(masterSecret, appKey, null, ClientConfig.getInstance());
43+
}
44+
45+
public ImageClient(String masterSecret, String appKey, HttpProxy proxy, ClientConfig conf) {
46+
_baseUrl = (String) conf.get(ClientConfig.PUSH_HOST_NAME);
47+
_imagesPath = (String) conf.get(ClientConfig.V3_IMAGES_PATH);
48+
String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
49+
this._httpClient = new NativeHttpClient(authCode, proxy, conf);
50+
}
51+
52+
/**
53+
* Upload image by url. Require at least one non-null url.
54+
*/
55+
public ImageUploadResult uploadImage(ImageUrlPayload imageUrlPayload)
56+
throws APIConnectionException, APIRequestException {
57+
Preconditions.checkArgument(imageUrlPayload.getImageType() != null, "Image type should not be null");
58+
checkImageUrlPayload(imageUrlPayload);
59+
NativeHttpClient client = (NativeHttpClient) _httpClient;
60+
String url = _baseUrl + _imagesPath + "/" + ImageSource.URL.value();
61+
JsonElement jsonElement = imageUrlPayload.toJSON();
62+
String content = _gson.toJson(jsonElement);
63+
ResponseWrapper responseWrapper = client.sendPost(url, content);
64+
if (responseWrapper.responseCode != 200) {
65+
LOG.error("upload image failed: {}", responseWrapper);
66+
}
67+
ImageUploadResult imageUploadResult = _gson.fromJson(responseWrapper.responseContent, ImageUploadResult.class);
68+
69+
LOG.info("upload image result:{}", imageUploadResult);
70+
return imageUploadResult;
71+
}
72+
73+
/**
74+
* Upload image by file. Require at least 1 non-null fileName. Currently only support Xiaomi and OPPO
75+
*/
76+
public ImageUploadResult uploadImage(ImageFilePayload imageFilePayload) {
77+
Preconditions.checkArgument(imageFilePayload.getImageType() != null, "Image type should not be null");
78+
checkImageFilePayload(imageFilePayload);
79+
NativeHttpClient client = (NativeHttpClient) _httpClient;
80+
String url = _baseUrl + _imagesPath + "/" + ImageSource.FILE.value();
81+
82+
Map<String, String> textMap = new HashMap<>();
83+
textMap.put("image_type", String.valueOf(imageFilePayload.getImageType().value()));
84+
85+
Map<String, String> fileMap = imageFilePayload.toFileMap();
86+
LOG.debug("upload fileMap: {}", fileMap);
87+
String response = client.formUploadByPost(url, textMap, fileMap, null);
88+
LOG.debug("upload image result: {}", response);
89+
ImageUploadResult imageUploadResult;
90+
try {
91+
imageUploadResult = _gson.fromJson(response, ImageUploadResult.class);
92+
} catch (JsonSyntaxException e) {
93+
LOG.error("could not parse response: {}", response);
94+
throw new IllegalStateException("could not parse response", e);
95+
}
96+
LOG.info("upload image result:{}", imageUploadResult);
97+
return imageUploadResult;
98+
}
99+
100+
/**
101+
* Modify image by url. Require at least one non-null url.
102+
*/
103+
public ImageUploadResult modifyImage(String mediaId, ImageUrlPayload imageUrlPayload)
104+
throws APIConnectionException, APIRequestException {
105+
Preconditions.checkArgument(StringUtils.isNotEmpty(mediaId), "mediaId should not be empty");
106+
checkImageUrlPayload(imageUrlPayload);
107+
NativeHttpClient client = (NativeHttpClient) _httpClient;
108+
String url = _baseUrl + _imagesPath + "/" + ImageSource.URL.value() + "/" + mediaId;
109+
JsonElement jsonElement = imageUrlPayload.toJSON();
110+
String content = _gson.toJson(jsonElement);
111+
ResponseWrapper responseWrapper = client.sendPut(url, content);
112+
if (responseWrapper.responseCode != 200) {
113+
LOG.error("upload image failed: {}", responseWrapper);
114+
}
115+
ImageUploadResult imageUploadResult = _gson.fromJson(responseWrapper.responseContent, ImageUploadResult.class);
116+
117+
LOG.info("upload image result:{}", imageUploadResult);
118+
return imageUploadResult;
119+
}
120+
121+
/**
122+
* Modify image by file. Require at least 1 non-null fileName. Currently only support Xiaomi and OPPO
123+
*/
124+
public ImageUploadResult modifyImage(String mediaId, ImageFilePayload imageFilePayload) {
125+
Preconditions.checkArgument(StringUtils.isNotEmpty(mediaId), "mediaId should not be empty");
126+
checkImageFilePayload(imageFilePayload);
127+
NativeHttpClient client = (NativeHttpClient) _httpClient;
128+
String url = _baseUrl + _imagesPath + "/" + ImageSource.FILE.value() + "/" + mediaId;
129+
130+
Map<String, String> fileMap = imageFilePayload.toFileMap();
131+
LOG.debug("upload image fileMap: {}", fileMap);
132+
String response = client.formUploadByPut(url, null, fileMap, null);
133+
LOG.debug("upload image result: {}", response);
134+
ImageUploadResult imageUploadResult;
135+
try {
136+
imageUploadResult = _gson.fromJson(response, ImageUploadResult.class);
137+
} catch (JsonSyntaxException e) {
138+
LOG.error("could not parse response: {}", response);
139+
throw new IllegalStateException("could not parse response", e);
140+
}
141+
LOG.info("upload image result:{}", imageUploadResult);
142+
return imageUploadResult;
143+
}
144+
145+
private void checkImageUrlPayload(ImageUrlPayload imageUrlPayload) {
146+
boolean anyUrlNotEmpty = StringUtils.isNotEmpty(imageUrlPayload.getImageUrl())
147+
|| StringUtils.isNotEmpty(imageUrlPayload.getFcmImageUrl())
148+
|| StringUtils.isNotEmpty(imageUrlPayload.getHuaweiImageUrl())
149+
|| StringUtils.isNotEmpty(imageUrlPayload.getOppoImageUrl())
150+
|| StringUtils.isNotEmpty(imageUrlPayload.getXiaomiImageUrl())
151+
|| StringUtils.isNotEmpty(imageUrlPayload.getJiguangImageUrl()) ;
152+
Preconditions.checkArgument(anyUrlNotEmpty, "Require at least 1 non-empty url");
153+
}
154+
155+
private void checkImageFilePayload(ImageFilePayload imageFilePayload) {
156+
boolean anyFileNotEmpty = StringUtils.isNotEmpty(imageFilePayload.getOppoFileName() )
157+
|| StringUtils.isNotEmpty(imageFilePayload.getXiaomiFileName() );
158+
Preconditions.checkArgument(anyFileNotEmpty, "Require at least 1 non-empty fileName. Currently only support Xiaomi and OPPO");
159+
}
160+
161+
162+
}

0 commit comments

Comments
 (0)