我尝试了许多不同的方法尝试使用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();
}
}
答案 0 :(得分:4)
经过大约20天的搜索和测试,我有一个有效的解决方案。 Android和Oracle都应该发布一个这样的简单评论示例,这样可以节省我和其他人很多时间。
在这篇文章中给予辛萌的信用,指出我正确的方向是关于标题,内容,请求的格式&#34;使用。
还可以在Can you explain the HttpURLConnection connection process?上获取jmort253的代码和他发布的解释(我修改了他的代码以适合我的项目)。
我现在是一个更好的程序员,因为我花时间试图理解为什么我的原始代码失败了。
下面是我的注释代码,用于将文本字符串发布到我的PHP脚本,我希望它可以帮助其他遇到问题的人。如果有人看到了改善的空间,请发表评论。:
在PHP方面:
$data = $_POST["values"]; // this gets the encoded and formatted string from the Android app.
在Android方面:
import java.net.HttpURLConnection;
// from another place in my code, I used:
// This calls the AsyncTask class below.
new POSTAsyncTask().execute();
//--------------------------------------------------
private class POSTAsyncTask extends AsyncTask<String, Integer, String>{
// AsyncTask<Params, Progress, Result>.
// Params – the type (Object/primitive) you pass to the AsyncTask from .execute()
// Progress – the type that gets passed to onProgressUpdate()
// Result – the type returns from doInBackground()
@Override
protected String doInBackground(String... params) {
String phpPOST = null; // make sure this variable is empty
try {
// deviceSIG is defined in another part of the code, and is a text string of values.
// below, the contents of deviceSIG are encoded and populated into the phpPOST variable for POSTing.
// the LACK of encoding was one reason my previous POST attempts failed.
phpPOST = URLEncoder.encode(deviceSIG, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
// Populate the URL object with the location of the PHP script or web page.
URL url = new URL("http://192.168.10.199/user_script.php");
// This is the point where the connection is opened.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// "(true)" here allows the POST action to happen.
connection.setDoOutput(true);
// I will use this to get a string response from the PHP script, using InputStream below.
connection.setDoInput(true);
// set the request method.
connection.setRequestMethod("POST");
// This is the point where you'll know if the connection was
// successfully established. If an I/O error occurs while creating
// the output stream, you'll see an IOException.
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
// write the formatted string to the connection.
// "values=" is a variable name that is passed to the PHP script.
// The "=" MUST remain on the Android side, and MUST be removed on the PHP side.
// the LACK of formatting was another reason my previous POST attempts failed.
writer.write("values=" + phpPOST);
// Close the output stream and release any system resources associated with this stream.
// Only the outputStream is closed at this point, not the actual connection.
writer.close();
//if there is a response code AND that response code is 200 OK, do stuff in the first if block
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
// otherwise, if any other status code is returned, or no status
// code is returned, do stuff in the else block
} else {
// Server returned HTTP error code.
}
// Get the string response from my PHP script:
InputStream responseStream = new
BufferedInputStream(connection.getInputStream());
BufferedReader responseStreamReader =
new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
// Close response stream:
responseStream.close();
result = response.toString();
// Disconnect the connection:
connection.disconnect();
//--------------------------------
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
return result; // when I had this as 'return null;', I would get a NullPointerException in String that equaled the result variable.
}
答案 1 :(得分:0)
Android 6.0建议使用HttpURLConnection发送HTTP请求,我在GitHub上的基于Android的食谱书制作示例项目:
https://github.com/xinmeng1/HttpUrlConnectionREST
包括发送GET / POST(表单数据或多部分)HTTP请求。如果你需要这本书,我可以发送相关的章节来使用HttpURLConnection。