【问题标题】:[Android]: How can I communicate with php server using httpUrlconnection post with data in outputStream and ensure that server gets in $_POST?[Android]:如何使用 httpUrlconnection post 与 outputStream 中的数据与 php 服务器通信并确保服务器进入 $_POST?
【发布时间】:2015-11-04 12:31:24
【问题描述】:

我正在使用 HttpURLConnection 将 json 查询传递给 php 服务器,但它不能按我想要的方式工作。

连接很好,我从服务器端得到了正确的错误响应,我确信 json 字符串得到了正确处理。例如: {"id":55,"date":"2011111","text":"","latitude":13.0,"longitude":123.0,"share":0,"image":"Image","sound":"sound"}

但是,php 服务器无法使用我发送的字符串加载变量 $_POST。 android端的代码很简单:

    String temp_p = gson.toJson(diary);
    URL url2 = new URL( "http://localhost:8080/****");
    HttpURLConnection connection = (HttpURLConnection)url2.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.connect();

    //Send request
    DataOutputStream wr = new DataOutputStream(
            connection.getOutputStream ());
    wr.writeBytes(temp_p);
    wr.flush();
    wr.close();

    //Get Response
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuffer response = new StringBuffer();
    while((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    rd.close();
    System.out.println("respons:" + response.toString());

php服务器上的代码如下:

if (isset($_POST['id'])) {
    $id = $_POST['id'];
    ..blablabla..
}
else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing"  ;
    $response["_POST"] = $_POST  ;
    echo json_encode($response);
}

在这种情况下,无论我发送什么,$_POST 都是 null ..

经过一番研究,我找到了一个解决方案,我必须修改服务器端的代码,如下所示:

$json = file_get_contents('php://input');
$request = json_decode($json, true);    
if (isset($request['id'])) {
    $id = $request['id'];

无需接触android代码,服务器就可以接收并处理我现在发送的json数据。

问题是我无法修改实际服务器上的代码。所以知道为什么 $_POST 没有得到 p

【问题讨论】:

    标签: php android json httpurlconnection


    【解决方案1】:

    您发送的是 json 格式的数据,但 不是 $_POST 数组,这就是 $_POST 为空的原因。如果您无法更改服务器端代码,那么您可以尝试我的 HttpConnection 类。希望这会奏效。

    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Map;
    
    public class HttpConnection {
        private HttpURLConnection conn;
        public static final int CONNECTION_TIMEOUT = 15 * 1000;
    
        public JSONObject sendRequest(String link, HashMap<String, String> values) {
    
        JSONObject object = null;
            try {
                URL url = new URL(link);
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(CONNECTION_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.connect();
    
                if (values != null) {
                    OutputStream os = conn.getOutputStream();
                    OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8");
                    BufferedWriter writer = new BufferedWriter(osWriter);
                    writer.write(getPostData(values));
    
                    writer.flush();
                    writer.close();
                    os.close();
                }
    
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream is = conn.getInputStream();
                    InputStreamReader isReader = new InputStreamReader(is, "UTF-8");
                    BufferedReader reader = new BufferedReader(isReader);
    
                    String result = "";
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        result += line;
                    }
    
    
                    if (result.trim().length() > 2) {
                        object = new JSONObject(result);
                    }
                }
            }
            catch (MalformedURLException e) {}
            catch (IOException e) {}
            catch (JSONException e) {}
            return object;
        }
    
        public String getPostData(HashMap<String, String> values) {
            StringBuilder builder = new StringBuilder();
            boolean first = true;
            for (Map.Entry<String, String> entry : values.entrySet()) {
                if (first)
                    first = false;
                else
                    builder.append("&");
                try {
                    builder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                    builder.append("=");
                    builder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                }
                catch (UnsupportedEncodingException e) {}
            }
            return builder.toString();
        }
    }
    

    通过调用sendRequest方法发出post请求。您只需传递链接,并使用HashMap发送数据。

    【讨论】:

    • 非常感谢您的回复,它确实有效。所以基本上我必须将数据编码为 url 代码的一部分,以便 $_POST 接收?
    • @user3040351 是的,伙计!!!你明白了。来自客户端的发送格式应与服务器端的接收格式匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多