我已经开始测试http客户端apache API。我需要它是因为我想发送请求并接收对virustotal API 的响应。病毒总API要求post请求中的参数:
- API 键值(每个用户的唯一值)
- 我从他们的网站上了解到的文件本身。
例如:
>>> url = "https://www.virustotal.com/vtapi/v2/url/scan"
>>> parameters = {"url": "http://www.virustotal.com",
... "apikey": "-- YOUR API KEY --"}
>>> data = urllib.urlencode(parameters)
>>> req = urllib2.Request(url, data)
目前,我正在尝试用 Java 而不是 Python 来做同样的事情。以下是我的源代码的一部分,经过注释以指导整个步骤:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//create post request
HttpPost request = new HttpPost("https://www.virustotal.com/vtapi/v2/file/scan");
//http json header
request.addHeader("content-type", "application/json");
String str = gson.toJson(param);
String fileName = UUID.randomUUID().toString() + ".txt";
try {
//API key
StringEntity entity = new StringEntity(str);
Writer writer = new BufferedWriter(new FileWriter(fileName));
writer.write(VirusDefinitionTest.malware());
request.setEntity(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody fileBody = new FileBody(new File(fileName));
builder.addTextBody("my_file", fileName);
HttpEntity entity = builder.build();
request.setEntity(entity);
HttpResponse response;
try {
response = httpClient.execute(request);
...
不幸的是,我收到 HTTP/1.1 403 Forbidden。显然,错误存在于实体中的某个地方,但我找不到如何做到这一点。任何帮助都将受到热烈欢迎。
最佳答案
这对我使用 Apache 4.5.2 HttpClient 有效:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("https://www.virustotal.com/vtapi/v2/file/scan");
FileBody bin = new FileBody(new File("... the file here ..."));
// the API key here
StringBody comment = new StringBody("5ec8de.....", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("apikey", comment)
.addPart("file", bin)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("ToString:" + EntityUtils.toString(resEntity));
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
重要的部分是 reqEntity
,它必须有两个专门命名的字段,“apikey”
和 “file”
。使用有效的 API key 运行此命令可以得到 API 的预期响应.
关于java - 如何使用 apache httpClient API 将文件 + api key 和其他参数作为单个请求发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304355/