با سلا و احترام
دوستان بنده میخواستم یک فایل xml رو به وسیله دستورات جاوا به یک وب سرویس ارسال کنم
معادل این دوستورات در php رو دارم ولی میخوام به زبان java باشه
کسی از دوستان میتونه در این زمینه برام کمک کنه
با سلا و احترام
دوستان بنده میخواستم یک فایل xml رو به وسیله دستورات جاوا به یک وب سرویس ارسال کنم
معادل این دوستورات در php رو دارم ولی میخوام به زبان java باشه
کسی از دوستان میتونه در این زمینه برام کمک کنه
بله، به راحتی امکان داره.
این لینک یه مثال سادش رو داره: https://www.mkyong.com/java/java-htt...ction-example/
https تفاوت خاصی با حالت ارسال http نداره در جاوا.
اگر مشکلی داشتی، کدی که نوشتی رو بفرست.
ممنون از جوابتون
کدی که به زبان php هست اینه
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSLCERT, $USER_CERTIFICATE_FILE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Client");
curl_setopt($ch, CURLOPT_URL,"https://site.com");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlStr);
$res = curl_exec($ch);
curl_close ($ch);
البته منظورم کد جاوایی بود که پس از کمی تلاش بهش رسیدید. به هر حال.
کد زیر رو نوشتم، تست هم کردم (البته به صورت http و local)، باید جواب بده:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
public class Sender {
public static void main(String[] args) {
Sender sender = new Sender();
String resp=sender.sendData(sender.openXML("file.xml"), "https://www.yourwebsite.com");
System.out.println(resp);
}
public String sendData(String data, String url) {
StringBuilder respText = new StringBuilder();
try {
HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(data.length()));
con.setRequestProperty("Content-Type", "application/xml; charset=\"utf-8\"");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeUTF(data);
out.flush();
out.close();
if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
BufferedReader in= new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
respText.append(line);
}
in.close();
}
} catch (IOException ex) {
Logger.getLogger(Sender.class.getName()).log(Level .SEVERE, null, ex);
}
return respText.toString();
}
public String openXML(String filePath) {
StringBuilder xmlText = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
xmlText.append(line);
}
} catch (IOException ex) {
Logger.getLogger(Sender.class.getName()).log(Level .SEVERE, null, ex);
}
return xmlText.toString();
}
private void InputStreamReader(InputStream inputStream) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
آخرین ویرایش به وسیله vahid-p : سه شنبه 22 فروردین 1396 در 23:07 عصر
بازم تشکر ازتون
منظور من از ssl این نیست که بعد از http یدونه s اضافه کنیم
منظور بنده اینه که برای ارسال درخواست باید بدونه فایل certificate هم با درخواست ارسال بشه
بی زحمت این سایت رو نگاه کنید
http://juliusdavies.ca/commons-ssl/ssl.html
مشکلش چیه؟
وب سرویسش رو خودت ننوشتی؟
وب سرویسش چیه؟؟
با سلام
وب سرویس مال یه شرکتی هست
من ننوشتم
در صورت امکان یک کانال ارتباطی بفرمایید تا بتوم بیشتر بهتون توضیح بدم
البته چک کردم HttpsURLConnection ارتباط با سروری که self-signed certification داشته باشه برقرار نمیکنه.
برای حل این مشکل سرچ زدم میشه متد main کلاس قبل رو اینطور تغییر داد: (البته خودم پیش نیومده برام و دقیق نمیدونم چنین کاری درسته هر certification ای رو قبول کنه)
public static void main(String[] args) { Sender sender = new Sender();
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.g etSocketFactory());
} catch (GeneralSecurityException e) {
}
String resp = sender.sendData(sender.openXML("file.xml"), "https://www.yourwebsite.com");
System.out.println(resp);
}
یدونه فایل pem هست
اونو باید ارسال کنیم
جوابی که میدم مطمئن نیستم چون همونطور که گفتم خودم قبلا با چنین چیزی مواجه نشدم.
ولی مثلا برای ساخت ربات تلگرام، کافیه فایل Certificate رو به صورت یکی از پارامترهای POST مثل بقیه بفرستید و تفاوتی با سایر فایلها نداره. ولی در اینترنت در خصوص این موضوع کارهای پیچیده ای داشت که من سر در نیاوردم.
اگر منظور شما از ارسال فایل به این صورت هست، کار خاصی نداره. اگر هم منظورتون چیز دیگه ایه، اطلاع ندارم. شاید سایر دوستان تجربه ای در این زمینه داشته باشن که میتونن کمک کنن.
امکان داره یه کانال ارتباطی از خودتون رو بفرمایید؟
یدونه نمونه کد پیدا کردم
بی زحمت نگاه کنید
public class AidapRequest {
static String POST = "POST";
static String TYPE = "Content-type:";
static String LEN = "Content-length:";
static String ENC = "Accept-Encoding:";
static String testcaseDir = "d:\\AIDAP\\requests";
static String resultsDir = "d:\\AIDAP\\responses";
static String testcaseFile = "testing";
static String urlString = "https://www.aidaptest.naimes.faa.gov/";
//static String urlString = "https://www.aidaptest.naimes.faa.gov/aidap/XmlNotamServlet";
//static String urlString = "";
// instance variables
boolean useGZIP = false;
static String postLine = "";
static String typeLine = "";
static String lenLine = "";
static String encodeLine = "";
static String queryLine = "";
static String keyStorePath = "D:\\Applications\\AA\\NMS\\aidap-collector\\aidapModule\\config\\properties\\aidapu ser_1f5d_2011_03_1192.pfx";
//static String keyStorePswd = "start123";
static String keyStorePswd = "UB#20abba";
/**
* Main Method
* @param args
*
*/
public static void main(String args[]) {
if (!readTC()) {
System.exit(-1);
}
HttpURLConnection httpURLConn = null;
BufferedOutputStream bos = null;
InputStream is = null;
URL url = null;
try {
// Setup connection
System.out.println("Accessing - " + urlString);
//urlString = postLine.substring(postLine.indexOf(POST) + POST.length(), postLine.indexOf("HTTP")).trim();
url = new URL(urlString);
// HTTPS connection
httpURLConn = (HttpURLConnection) url.openConnection();
// HTTPS (with client certificate)
if (httpURLConn instanceof HttpsURLConnection) {
// take care of server certificate does match hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname,
SSLSession session) {
return true;
}
public boolean verify(String hostname, String temp) {
return true;
}
};
((HttpsURLConnection) httpURLConn).setHostnameVerifier(hv);
// set to always trust the server
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] arg0,
String arg1)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0,
String arg1)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public boolean isClientTrusted(X509Certificate[] arg0) {
return true;
}
public boolean isServerTrusted(X509Certificate[] arg0) {
return true;
}
};
// use the client certificate
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(new File(keyStorePath)),
keyStorePswd.toCharArray());
KeyManagerFactory kmf =
KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, keyStorePswd.toCharArray());
// Set socket context and setup socket factory
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(),
new TrustManager[]{tm},
null);
SSLSocketFactory sockFactory = context.getSocketFactory();
((HttpsURLConnection) httpURLConn).setSSLSocketFactory(sockFactory);
} else {
System.err.println("Go - else not https");
}
// Set up request parameters
httpURLConn.setAllowUserInteraction(false);
httpURLConn.setDoInput(true);
httpURLConn.setDoOutput(true);
httpURLConn.setUseCaches(false);
httpURLConn.setRequestProperty(typeLine.substring( 0, typeLine.indexOf(":")).trim(),
typeLine.substring(typeLine.indexOf(":") + 1).trim());
//if (!encodeLine.equals("")) {
// httpURLConn.setRequestProperty(encodeLine.substrin g(0, encodeLine.indexOf(":")).trim(),
// encodeLine.substring(encodeLine.indexOf(":") + 1).trim());
//}
httpURLConn.setRequestMethod(POST);
if (queryLine == null || queryLine.length() == 0) {
httpURLConn.setRequestMethod("GET");
}
// Connect to server
System.out.println("Connecting to server...");
httpURLConn.connect();
System.out.println("Send request to server");
// Write HTTP Request
if (queryLine.length() > 0) {
bos = new BufferedOutputStream(httpURLConn.getOutputStream() );
byte[] buf = queryLine.getBytes();
bos.write(buf, 0, buf.length);
bos.flush();
}
//Read HTTP Response
System.out.println("Read response from server...");
is = new BufferedInputStream(httpURLConn.getInputStream());
// read-in appropriately based on whether returned data
// has content encoding gzip
String contentEncoding = httpURLConn.getContentEncoding();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
try {
if (is.markSupported()) {
is.mark(2);
}
is = new GZIPInputStream(is);
} catch (IOException e) {
if (is.markSupported()) {
is.reset();
}
is = new BufferedInputStream(is);
}
}
// Read the response in
System.out.println("Starting read");
byte[] buff = new byte[8192];
int numOfBytes;
boolean downloading = true;
int loaded = 0;
FileOutputStream fileWriter = new FileOutputStream(resultsDir + "\\" + testcaseFile + "_out.txt");
System.out.println("Start write");
while ((numOfBytes = is.read(buff)) > 0) {
fileWriter.write(buff, 0, numOfBytes);
}
fileWriter.close();
System.err.println("End of run");
} catch (IOException e) {
System.err.println("io error: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.err.println("exception: " + e.getMessage());
e.printStackTrace();
} finally {
// Close input stream
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
is = null;
}
// Close output stream
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
}
bos = null;
}
// Close connection
if (httpURLConn != null) {
httpURLConn.disconnect();
httpURLConn = null;
}
}
} //end of go()
/**
*
* @return
*/
private static boolean readTC() {
postLine = "POST /aidap/XmlNotamServlet HTTP/1.1";
typeLine = "Content-type: application/x-www-form-urlencoded";
lenLine = "Content-length: <input_parameter’s length>";
encodeLine = "Accept-Encoding: gzip";
queryLine = "uid=AAITSTST&password=xxxx&location_id=KDFW";
return true;
}
}
اینم تقریبا شبیه همونیه که برای self-signed فرستادم و متد main رو تغییر دادم. اگر اولی جواب نداد (که ساده تر بود) میشه از دومی استفاده کرد.
در هیچ کدوم از این دو مورد فایل pem ارسال نمیشه و برای دور زدن HttpsURLConnection هست که با trusted ها ارتباط برقرار میکنه نه self-signed ها.
به نظرم شما اولی (پست شماره 8) رو تست کنید، احتمالا جواب بگیرید (خودم قبلش نتونستم از یک آدرس self-signed اطلاعات بگیرم، ولی بعد با کد پست 8 خیلی راحت جواب گرفتم)
موفق باشید
در کدهایی که بنده ارسال کردم ، فایل certificate این هست
static String keyStorePath = "D:\\Applications\\AA\\NMS\\aidap-collector\\aidapModule\\config\\properties\\aidapu ser_1f5d_2011_03_1192.pfx";
فایل certificate بنده هم پسوندش p12 هست که بنده pem عرض کرده بودم
آخرین ویرایش به وسیله sadeghzadeh82 : پنج شنبه 24 فروردین 1396 در 21:14 عصر
خب اگر جواب میده خوبه.
از خط 117
// Set up request parameters
به بعد هم که یک ارسال/دریافت عادیه که مثل کد پست 4 میتونید ارسال کنید یا هر جور دیگه که دوست داشتید.
موفق باشید