имеется XML файл match.xml, через curl легко отправить POST и добавить в базу.
curl -F "xml=@match.xml" web_url
Стандартная реализация POST на Java возвращает мне POST Response Code :: 400 Bad Request
public static void sendPOST(String data) throws IOException {
URL obj = new URL(FinalConstants.BETRADAR_UPLOAD);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(data.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
и при таких настройках возвращает такую же ошибку
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "text/xml");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
Подскажите как работает curl -F
? Как мне корректно отправить данные ?
UPD
Несколько вариантов попробовал с HttpClient и все они выдают следующее
HttpResponseProxy{HTTP/1.1 400 Bad Request [Server: nginx, Date: Thu, 09 Feb 2017 20:07:18 GMT, Content-Type: application/octet-stream, Content-Length: 0, Connection: keep-alive]}
1 Вариант
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(FinalConstants.UPLOAD);
HttpEntity entity =
new ByteArrayEntity(data.getBytes("UTF-8"),
ContentType.TEXT_XML);
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
2 вариант
InputStream in ;
StringEntity entity = new StringEntity(data, ContentType.create(
"text/xml", Consts.UTF_8));
entity.setChunked(true);
HttpPost httppost = new HttpPost( FinalConstants.UPLOAD);
httppost.setEntity(entity);
HttpClient client = HttpClients.createDefault();
HttpResponse response = client.execute(httppost);
System.out.println(response.toString());
in=response.getEntity().getContent();
String body = IOUtils.toString(in);
System.out.println(body);
Также вариант с использованием файла
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM, // Также как и с другими типами
f.getName()
);
Все таки мне хотелось бы отправить строку, а не файл
UPD2
public static void sendPOST(File file) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpPost uploadFile = new HttpPost(FinalConstants.UPLOAD);
final HttpEntity entity = MultipartEntityBuilder
.create()
.addBinaryBody("xml", file).build();
uploadFile.setEntity(entity);
final HttpResponse response = httpClient.execute(uploadFile);
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
java.lang.NoSuchMethodError: org.apache.http.entity.ContentType.create(Ljava/lang/String;[Lorg/apache/http/NameValuePair;)Lorg/apache/http/entity/ContentType;
at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:219)
at org.apache.http.entity.mime.MultipartEntityBuilder.build(MultipartEntityBuilder.java:240)