我有一个简单的POST:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#define NEWLINE() printf("\n");
#define DIVIDER() printf("============================================================================\n");
#define PL(l) printf("LINE: %s\n", l);
int const MAX_PROCESSES = 20;
int const BUFFER_SIZE = 1024;
int exhaustedLine(char* line) {
if (line[sizeof line - 1] == '\0' && line[sizeof line - 2] != '\n') {
printf("n:%c 0:%c\n", line[sizeof line - 2], line[sizeof line - 1]);
NEWLINE();
return -1;
}
return 0;
}
int main(int argc, char const *argv[]) {
FILE* fp = popen("ps -ev", "r");
char buf[BUFFER_SIZE];
char* line = (char*)1;
while (line) {
DIVIDER();
line = fgets(buf, BUFFER_SIZE, fp);
PL(line);
if (exhaustedLine(line) != 0) {
printf("END OF LINE\n");
}
}
return 0;
}
我必须支持UTF-8编码,而String url = "https://mysite";
try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
URIBuilder uriBuilder = new URIBuilder(url);
HttpPost request = new HttpPost();
List<NameValuePair> nameValuePairs = new ArrayList<>(params);
request.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8.name()));
String encodedAuthorization = URLEncoder.encode(data, StandardCharsets.UTF_8.name());
request.addHeader("Authorization", encodedAuthorization);
try (CloseableHttpResponse response = httpClient.execute(request)) {
编码还不够,但是尚不清楚必须执行以下几种操作必须
使用UrlEncodedFormEntity
:
uriBuilder.setCharset
使用HttpPost request = new HttpPost(uriBuilder.setCharset(StandardCharsets.UTF_8)).build());
参数:
http.protocol.content-charset
或者仅添加Content-Type"` header:
HttpPost request = new HttpPost(uriBuilder.setParameter("http.protocol.content-charset", "UTF-8").build());
request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
还是我忽略了其他明显的解决方案?
答案 0 :(得分:0)
// Method to encode a string value using `UTF-8` encoding scheme
private static String encodeValue(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex.getCause());
}
}
public static void main(String[] args) {
String baseUrl = "https://www.google.com/search?q=";
String query = "Hellö Wörld@Java";
String encodedQuery = encodeValue(query); // Encoding a query string
String completeUrl = baseUrl + encodedQuery;
System.out.println(completeUrl);
}
}
https://www.google.com/search?q=Hell%C3%B6+W%C3%B6rld%40Java
我认为这可能是解决方案。
您已经在上面提到:https://www.urlencoder.io/java/
答案 1 :(得分:0)
要正确编码,我将在List<NameValuePair>
上使用URIBuilder
中的参数
然后使用
进行编码URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8.name());