-
Notifications
You must be signed in to change notification settings - Fork 210
/
AbstractHttpAttribute.java
94 lines (84 loc) · 2.76 KB
/
AbstractHttpAttribute.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.swjtu.http;
import com.swjtu.lang.LANG;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* AbstractHttpAttribute is an abstract base class associated with HTTP.
*
* @see com.swjtu.trans.AbstractTranslator
* @see com.swjtu.tts.AbstractTTS
*/
public abstract class AbstractHttpAttribute {
public String url;
public Map<String, String> formData;
public Map<LANG, String> langMap;
public CloseableHttpClient httpClient;
public AbstractHttpAttribute(String url) {
this.url = url;
this.formData = new HashMap<>();
this.langMap = new HashMap<>();
this.httpClient = HttpClients.createDefault();
}
/**
* Execute the translation or TTS task (send a POST or GET request to the server),
* receive the result of translation or speech conversion., and return the content
* or save file name as string.
*
* @return the string form of the translated result.
* @throws Exception if the request fails
*/
public abstract String query() throws Exception;
/**
* The control center includes parameter setting, sending HTTP request, receiving
* and saving audio data.
*
* @param source source language
* @param text the content to be converted into speech
* @return the string form of the translated result.
*/
public abstract String run(LANG source, String text);
/**
* The control center includes parameter setting, sending HTTP request, receiving
* and parsing text data.
*
* @param from source language
* @param to target language
* @param text the content to be translated
* @return the string form of the translated result.
*/
public abstract String run(LANG from, LANG to, String text);
/**
* Release and close the resources of HTTP
* @param httpEntity http entity
* @param httpResponse http response
*/
public void close(HttpEntity httpEntity, CloseableHttpResponse httpResponse) {
try {
EntityUtils.consume(httpEntity);
if (null != httpResponse) {
httpResponse.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Release and close the resources of HTTP
*/
public void close() {
try {
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}