【发布时间】:2011-07-12 13:15:13
【问题描述】:
在我的应用程序中,我想将我的 android 应用程序 XML 数据发布到使用 REST 服务的远程服务器中。我的代码如下:
String url = "api.example.com";
int port = 443;
String query = "<?xml version='1.0' encoding='UTF-8'?><request><client><name>APIappDevAccount</name><password>123456</password></client><user><name>foyzulkarim</name><password>123456</password><groupId>12345</groupId></user></request>";
Socket socket = null;
try {
socket = new Socket(url,port);
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
PrintStream pw = null;
try {
pw = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.print("POST api.example.com/rest/rest/user");
pw.print("Content-Type: application/xml");
pw.print("Content-Length:" + query.length());
pw.print(query);
System.out.println("hello foysal.");
//get result
String l = null;
String text="";
try {
while ((l=br.readLine())!=null) {
System.out.println(l);
text+=l;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.close();
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但是该服务器在 SSL/HTTPS 协议之后,所以我收到以下 400 Bad Request 作为响应。
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>400 Bad Request</title></head><body><h1>Bad Request</h1><p>Your browser sent a request that this server could not understand.<br />Reason: You're speaking plain HTTP to an SSL-enabled server port.<br />Instead use the HTTPS scheme to access this URL, please.<br /><blockquote>Hint: <a href="https://api.example.com/"><b>https://api.example.com/</b></a></blockquote></p></body></html>
如果我像下面这样使用 SSLSocketFactory
SocketFactory socketFactory = SSLSocketFactory.getDefault();
Socket socket = null;
try {
socket = socketFactory.createSocket(url, port);
我遇到了异常
javax.net.ssl.SSLException: Not trusted server certificate
java.security.cert.CertPathValidatorException: TrustAnchor for CertPath not found.
一行
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
我的问题是,在上述场景中,如何通过 SSL 从 android 应用程序发布数据? 我想我们很多人都面临这个问题,所以我请求你给我/我们一些详细的答案。干杯。
【问题讨论】:
标签: sockets post ssl restful-authentication