我尝试了许多不同的方法,试图使用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();
}
}
Android 6.0建议使用HttpURLConnection来发送HTTP请求,我基于GitHub上的Android菜谱制作了一个示例项目:
https://github.com/xinmeng1/HttpUrlConnectionREST
其中包括发送GET/POST(表单数据或多部分)HTTP请求。如果您需要这本书,我可以发送有关HttpURLConnection用法的章节。
经过大约20天的搜索和测试,我有了一个可行的解决方案。Android和Oracle都应该发布这样一个简单的注释示例,它会为我和其他人节省很多时间。
在这篇文章中,欣蒙为我指出了“请求的标题、内容和格式”的正确方向。
功劳也归于jmort253 on能否解释一下HttpURLConnection的连接过程?因为他的代码和他发布的解释(当然,我修改了他的代码以适应我的项目)。
我现在是一个更好的程序员,因为我花时间试图理解为什么我的原始代码失败了。
以下是我注释的代码,用于将文本字符串发布到我的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.
}
问题内容: 在CSS中,任何图像路径都相对于CSS文件位置。 f.ex如果我放入CSS文件并使用类似 浏览器将查找有意义的图像。 是否可以在javascript中做同样的事情? F.ex如果我包括以下代码并将其放在其中: 找不到图片,因为浏览器使用HTML文件作为起点,而不是脚本位置。我希望能够像CSS一样使用脚本位置作为起点。 这可能吗? 问题答案: 按照上面的方法在DOM中搜索您自己的标记是可
问题内容: 我有一个名为“ gcc_opt.pyw”的Python脚本,并将其目录包含在Windows PATH环境变量中。 但是不会将单个命令行参数传递给脚本。打印出sys.argv会告诉我argv列表中只有文件名。 该命令: 结果是 你能告诉我为什么没有其他论点吗? 我不知道它是否重要,但是我将python.exe设置为执行.pyw文件的默认程序,因为我看不到使用pythonw.exe的任何打
问题内容: 我从PHP脚本执行Python脚本时遇到问题。我的客户端使用Bluehost,因此我使用在此描述的easy_install方法为Python安装了第三方模块(numpy):https ://my.bluehost.com/cgi/help/530?step = 530 为了演示我的问题,我创建了两个python脚本和一个PHP脚本。 hello.py包含: hello-numpy.py
我正在使用以下脚本执行Rest调用。我让它在另一个Jenkins装备上工作,现在正在改进脚本,使其在另一个装备上可重用,但我得到了一个异常抛出。我遇到问题的代码如下。看起来它在“new HTTPBuilder()”结构上爆炸了,但我不明白为什么: 我得到的堆栈跟踪如下所示: FATAL: groovy/lang/闭包java.lang.NoClassDefFoundError: groovy/la
问题内容: 我可以使用Groovy脚本获取响应xml。我需要获取请求XML,因为我需要在soap ui测试中添加“断言脚本”。 我正在使用以下代码来获取响应xml 但是我不确定如何获取SOAPUI的请求xml。谁能帮我获得SOPAUI的请求xml吗? 问题答案: 要以字符串形式获取请求内容,可以使用 有关SoapUI API的更多信息,请访问http://www.soapui.org/apidoc
问题内容: 我很确定答案是否定的,但是我想我还是会问。 如果我的站点引用了名为“ whatever.js”的脚本,是否可以从该脚本中获取“ whatever.js”?喜欢: 麻烦多于依赖检查所值得的,但是这真是麻烦。 问题答案: var scripts = document.getElementsByTagName(‘script’); var lastScript = scripts[scrip