JSON:
public String sendRequest(String request, String url, String token) throws IOException {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(request, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpPost.setHeader("authorization", "Bearer " + token);
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int bytesRead;
try {
while ((bytesRead = is.read(buffer, 0, 1024)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
byte[] rep = baos.toByteArray();
String reponse = new String(rep, "UTF-8");
return reponse;
}
文件:
......
httpPost.setEntity(MultipartEntityBuilder.create().addBinaryBody("file", file, ContentType.DEFAULT_BINARY, fileName).build());
......