【问题标题】:HttpURLConnection PHP script not getting dataHttpURLConnection PHP脚本没有获取数据
【发布时间】: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


【解决方案1】:

Android 6.0 建议使用 HttpURLConnection 发送 HTTP 请求,我根据 GitHub 上的 Android 食谱书做了一个示例项目:

https://github.com/xinmeng1/HttpUrlConnectionREST

其中包括发送 GET/POST(表单数据或多部分)HTTP 请求。如果您需要这本书,我可以发送相关章节以供 HttpURLConnection 使用。

【讨论】:

  • 非常感谢您的浏览和回复。我去看看你的github帖子,但是我不知道如何将它集成到我的项目中,因为我对使用HttpURLConnection的正确方法的理解有限。
  • 查看示例后,您会发现它非常简单。该示例已将其封装到一个实用程序类 (.util.RestUtil) 中。您可以将名为util的包中的所有文件复制下来,然后在活动中模仿使用。比如你想用POST,你就模仿this file中的用法
  • 使用这个工具有 4 个步骤: 1. 准备 POST 的参数。 2. 用参数构造RestTask postTask。 3.增加回调函数。 4. 执行异步任务。
  • 如果想了解使用HttpURLConnection发送HTTP请求的原理,就需要了解HTTP请求的基本知识。(请求头、内容、格式……)第一。然后您可以使用其中一个包捕获工具(我认为 Fiddler2 最适合 Android)来尝试捕获一些包来调试您的项目。顺便说一句,java回调理论对于理解AsyncTask也很重要。
【解决方案2】:

经过大约 20 天的搜索和测试,我有了一个可行的解决方案。 Android 和 Oracle 都应该发布一个这样的简单注释示例,它会为我和其他人节省很多时间。

感谢 Xin Meng 在这篇文章中为我指明了使用“请求的标题、内容和格式”的正确方向。

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.          
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 2014-07-20
    • 2016-02-24
    • 2016-10-21
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2018-05-19
    相关资源
    最近更新 更多