【发布时间】:2016-04-28 08:17:50
【问题描述】:
我尝试了许多不同的方法来尝试使用 HttpURLConnection 将数据从我的 Android 应用程序上传到服务器上的 PHP 脚本,但在服务器上由 PHP 创建的文件中没有显示任何内容。我使用 HTTPClient 取得了成功,但我不得不切换到使用 HttpURLConnection。该应用程序在运行时不会崩溃。我确信我忽略了一些简单的事情。我的 PHP 脚本运行良好,甚至返回了预期的响应,但是我还没有看到我的 Android 代码有问题。感谢您提供任何帮助。
这是 PHP 脚本的开头:
$data = $_POST["deviceSIG"];
这是我用来将数据上传到 PHP 脚本的代码:
// the string deviceSIG is defined elsewhere and has been defined in the class.
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... params)
try{
URL url = new URL("http://192.168.10.199/user_script.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
OutputStream outputStream = conn.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(deviceSIG);
writer.close();
outputStream.close();
// read response
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) { response.append(inputLine); }
in.close();
result = response.toString();
// disconnect
conn.disconnect();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//-------------------------------------------------------------------------------
protected void onProgressUpdate(Integer... progress){
progBar.setProgress(progress[0]);
}
//-------------------------------------------------------------------------------
protected void onPostExecute(String result){
progBar.setVisibility(View.GONE);
String rawEcho = result;
String[] Parts = rawEcho.split("~");
String echo = Parts[1];
String UIID = "User ID: " + echo;
try {
FileOutputStream fOS = openFileOutput("Info.txt", Context.MODE_APPEND);
fOS.write(newLine.getBytes());
fOS.write(UIID.getBytes());
fOS.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
为什么不使用 volley 库?
-
非常感谢您的浏览和回复。我不依赖库的原因是:如果我了解我的代码为什么会这样做,以及为什么它可能会崩溃,它会让我成为一个更好的程序员;我不知道如何调整/按摩库以与许多不同类型的 Android 设备一起使用,例如我正在进行的项目现在在我的智能手机上运行良好,但需要调整才能在我的平板电脑上运行。
标签: php android httpurlconnection