Статус: Новичок
Группы: Участники
Зарегистрирован: 29.09.2013(UTC) Сообщений: 6 Сказал(а) «Спасибо»: 1 раз Поблагодарили: 1 раз в 1 постах
|
Добрый день. Стоит задача написать модуль интеграции с ООС на JAVA. В документации с сайта написано, что POST запрос должен быть следующей структуры (последний блок с ЭЦП необязателен): Цитата:POST /pgz/services/upload HTTP/1.1 Content-Type: multipart/form-data; boundary=---------------------------7db10b11c0824 Host: zakupki.gov.ru Content-Length: (размер содержимого) Connection: Keep-Alive Cache-Control: no-cache -----------------------------7db10b11c0824 Content-Disposition: form-data; name="login" (имя пользователя) -----------------------------7db10b11c0824 Content-Disposition: form-data; name="password" (пароль) -----------------------------7db10b11c0824 Content-Disposition: form-data; name="document"; filename="(имя файла)" Content-Type: text/xml (XML-документ) -----------------------------7db10b11c0824 Content-Disposition: form-data; name="signature"; filename="(имя файла)" Content-Type: application/octet-stream (ЭЦП) -----------------------------7db10b11c0824 После установки КриптоПро JCP 2.0 пытаюсь выполнить POST запрос: Код:package SSLTesting;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
*
* @author artem
*/
public class HttpsTest {
private static HttpsURLConnection httpsConnection;
private static HttpURLConnection httpConnection;
private static String boundary = Long.toHexString(System.currentTimeMillis());
static {
try {
TrustManager[] trustAllCerts = { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = SSLContext.getInstance("GostTLS");
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception localException) {
localException.printStackTrace();
}
}
private static void doPost(String s) throws IOException {
try {
httpsConnection = (HttpsURLConnection) new URL("https://zakupki.gov.ru/pgz/services/upload").openConnection();
httpsConnection.setRequestMethod("POST");
httpsConnection.setDoOutput(true);
httpsConnection.addRequestProperty("Content-Type", "multipart/form-data; boundary=--" + boundary);
httpsConnection.addRequestProperty("User-Agent", "Mozilla/3.0 (compatible; Indy Library)");
httpsConnection.addRequestProperty("Connection", "keep-alive");
httpsConnection.addRequestProperty("Content-Length", "" + s.length());
OutputStreamWriter writer = new OutputStreamWriter(httpsConnection.getOutputStream());
writer.write(s);
writer.flush();
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
writer.close();
reader.close();
httpsConnection.disconnect();
} catch (Exception e) {
InputStream errorStream = httpsConnection.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(errorStream));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
System.out.println(httpsConnection.getResponseCode());
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
String CRLF = "\r\n";
StringBuilder sb = new StringBuilder();
sb.append("--" + boundary).append(CRLF);
sb.append("Content-Disposition: form-data; name=\"login\"").append(CRLF);
sb.append(CRLF);
sb.append("test").append(CRLF);
sb.append("--" + boundary).append(CRLF);
sb.append("Content-Disposition: form-data; name=\"password\"").append(CRLF);
sb.append(CRLF);
sb.append("test").append(CRLF);
sb.append("--" + boundary).append(CRLF);
sb.append("Content-Disposition: form-data; name=\"document\"; filename=\"test.xml\"").append(CRLF);
sb.append("Content-Type: text/xml").append(CRLF);
sb.append(CRLF);
sb.append("<xml >").append(CRLF);
sb.append("--" + boundary).append(CRLF);
sb.append("Content-Disposition: form-data; name=\"signature\"; filename=\"(file.file)\"").append(CRLF);
sb.append("Content-Type: application/octet-stream ").append(CRLF);
sb.append(CRLF);
sb.append("streamstreamstream").append(CRLF);
sb.append("--" + boundary);
doPost(sb.toString());
}
}
Запрос получается такого содержания: Цитата:--141774c56c6 Content-Disposition: form-data; name="login"
test --141774c56c6 Content-Disposition: form-data; name="password"
test --141774c56c6 Content-Disposition: form-data; name="document"; filename="test.xml" Content-Type: text/xml
<xml > --141774c56c6 Content-Disposition: form-data; name="signature"; filename="(file.file)" Content-Type: application/octet-stream
streamstreamstream --141774c56c6 На строке Код:ufferedReader reader = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
вываливается исключение: Цитата:java.io.IOException: Server returned HTTP response code: 500 for URL: https://zakupki.gov.ru/pgz/services/uploadat sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1626) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) Может кто-то сталкивался с подобной проблемой и уже решил ее? Отредактировано пользователем 2 октября 2013 г. 7:41:38(UTC)
| Причина: Не указана
|
|
|
|
Статус: Новичок
Группы: Участники
Зарегистрирован: 29.09.2013(UTC) Сообщений: 6 Сказал(а) «Спасибо»: 1 раз Поблагодарили: 1 раз в 1 постах
|
Всем спасибо за внимание тему можно закрывать.
|
1 пользователь поблагодарил artem24 за этот пост.
|
|
|
Статус: Участник
Группы: Участники
Зарегистрирован: 10.12.2013(UTC) Сообщений: 10
Сказал(а) «Спасибо»: 1 раз
|
Автор: artem24 Всем спасибо за внимание тему можно закрывать. Привет, не знаю, получишь ли ты сообщение, но у меня абсолютно аналогичная проблема, очень интересно в чём была твоя ошибка.
|
|
|
|
Статус: Новичок
Группы: Участники
Зарегистрирован: 29.09.2013(UTC) Сообщений: 6 Сказал(а) «Спасибо»: 1 раз Поблагодарили: 1 раз в 1 постах
|
Автор: E1ektr0 Привет, не знаю, получишь ли ты сообщение, но у меня абсолютно аналогичная проблема, очень интересно в чём была твоя ошибка. Насколько я понял если использовать HttpsURLConnection для формирования и отправки multipart/form-data пакета, то сервер не воспринимает его как multipart/form-data, от чего и возникает ошибка. Поэтому был использован CloseableHttpClient от Apache, понадобятся: httpclient-4.3.jar, httpclient-cache-4.3.jar, httpcore-4.3.jar, httpmime-4.3.jar. Код:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class SSLTest {
private RequestConfig config = null;
private static String boundary = Long.toHexString(System.currentTimeMillis());
private CloseableHttpClient httpclient = null;
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
private String ServerResponse;
private String Host = "https://zakupki.gov.ru/pgz/services/upload";
public static void main(String[] args){
SSLTest test = new SSLTest();
try{
test.testSend();
} catch (Exception e){
e.printStackTrace();
}
}
public void testSend() throws IOException, Exception{
String fileBody = "somedata";
HttpPost httppost = new HttpPost(Host);
if(config == null) {
initConfig();
}
httppost.setConfig(config);
httppost.setHeader("Cache-Control", "no-cache");
httppost.setHeader("Connection", "keep-alive");
httppost.setHeader("User-Agent", "Mozilla/3.0 (compatible; Indy Library)");
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setBoundary(boundary);
entity.addTextBody("login", "Login");
entity.addTextBody("password", "Pass");
entity.addBinaryBody("document", fileBody.getBytes(), ContentType.TEXT_HTML, "file0.xml");
entity.addTextBody("signature", "Sign");
httppost.setEntity(entity.build());
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.writeTo(baos);
ServerResponse = baos.toString("Utf-8");
}
EntityUtils.consume(resEntity);
response.close();
if(response.getStatusLine().getStatusCode() != 200) {
System.err.println("Server return error status: " + response.getStatusLine());
} else {
System.out.println(ServerResponse);
}
}
private static SSLContext getSSLContext() {
try {
TrustManager[] trustAllCerts = { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = SSLContext.getInstance("GostTLS");
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
return sc;
} catch (Exception localException) {
localException.printStackTrace();
}
return null;
}
private void initConfig() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(getSSLContext(),
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
config = RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
}
}
|
|
|
|
Быстрый переход
Вы не можете создавать новые темы в этом форуме.
Вы не можете отвечать в этом форуме.
Вы не можете удалять Ваши сообщения в этом форуме.
Вы не можете редактировать Ваши сообщения в этом форуме.
Вы не можете создавать опросы в этом форуме.
Вы не можете голосовать в этом форуме.
Important Information:
The Форум КриптоПро uses cookies. By continuing to browse this site, you are agreeing to our use of cookies.
More Details
Close