希望有些人可以帮助我解决“脑死锁”的问题。
(只是为了理解)我正在尝试使用php脚本接收数据库。因此,我必须调用一个Web地址/服务器,该服务器仅在我使用有效的用户名/密码组合并发送正确的参数时才能访问php脚本。
当使用HttpClient和HttpPost时,我的代码运行良好。 (下面是GOOD代码)
我需要的是一个InputStream,然后我可以将其保存/复制到Android手机上(如工作代码中所示)。但现在我得到的结果是一个IOException。一旦调用urlconn.getInputStream(),Activity就会中止。但getOutputStream()也没有有效值。
现在来到问题。有人可以检查我的代码并告诉我如何正确地POST参数吗?另外,您是否知道我是否可以通过URL发送身份验证?特别是HTTP'S'部分引起了我的兴趣。对于非安全模式,我已经有一个运行中的解决方案。
谢谢你的帮助!
InputStream myInputDB = null;
OutputStream myOutputDB = null;
HttpResponse response = null;
// Path to the just created empty db
String dbFilePath = DB_PATH + KeyConstants.DB_NAME;
try {
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("version", "20110516140000"));
HttpPost httppost = new HttpPost("http://USERNAME:PASSWORD@SomeAdress/u/db2.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httppost);
//Open your local db as the input stream
myInputDB = response.getEntity().getContent();
//Open the empty db as the output stream
myOutputDB = new FileOutputStream(dbFilePath);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInputDB.read(buffer)) > 0) {
myOutputDB.write(buffer, 0, length);
}
//Close the streams
myOutputDB.flush();
myOutputDB.close();
myInputDB.close();
现在我正在尝试使用HttpURLConnection/HttpsURLConnection代替上面的解决方案。为什么要这样做很清楚,因为实时系统使用HTTPS(服务器认证)。
到目前为止,我已经浪费了数天的时间来弄清楚如何...
- 使用HttpURLConnection POST参数
- 在服务器上进行身份验证
- 一般情况下避免认证检查(用于测试!)
但我不知道我犯了什么错误。以下是我的代码...
String urlString = "http://USERNAME:PASSWORD@SomeAdress/u/db2.php";
String params = "version=20110516140000";
InputStream stream = null;
url = new URL(urlString);
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection urlconn = (HttpsURLConnection) url.openConnection();
urlconn.setHostnameVerifier(DO_NOT_VERIFY);
urlconn.setDoInput(true);
urlconn.setDoOutput(true);
urlconn.setRequestMethod("POST");
urlconn.setRequestProperty("Content-Type", "text/xml");
urlconn.setRequestProperty("Content-Length", String.valueOf(params.getBytes().length));
OutputStreamWriter wr = new OutputStreamWriter(urlconn.getOutputStream());
wr.write(params);
wr.flush();
stream = urlconn.getInputStream();
if ("gzip".equals(urlconn.getContentEncoding())) {
stream = new GZIPInputStream(stream);
}
wr.close();
} else {
// Almost the same as if-path, but without trustAllHosts() and with HttpURLConnection instead of HttpsURLConnection
}
return stream;
我需要的是一个InputStream,然后我可以将其保存/复制到Android手机上(如工作代码中所示)。但现在我得到的结果是一个IOException。一旦调用urlconn.getInputStream(),Activity就会中止。但getOutputStream()也没有有效值。
现在来到问题。有人可以检查我的代码并告诉我如何正确地POST参数吗?另外,您是否知道我是否可以通过URL发送身份验证?特别是HTTP'S'部分引起了我的兴趣。对于非安全模式,我已经有一个运行中的解决方案。
谢谢你的帮助!