[Android]: How can I communicate with php server using httpUrlconnection post with data in outputStream and ensure that server gets in $_POST?

旧时模样 提交于 2019-12-25 03:52:49

问题


I am using HttpURLConnection to pass json query to php server and it doesn't work the way I want.

The connection is fine, I got proper error respond from server side and I am sure the json string is properly handled. eg: {"id":55,"date":"2011111","text":"","latitude":13.0,"longitude":123.0,"share":0,"image":"Image","sound":"sound"}

However, the php server cannot load the variable $_POST with the string that I have sent. The code on android side is simple:

    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());

The code on php server looks like:

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);
}

The $_POST is null in this case no matter what I sent ..

And after reaserching a bit, I found a solution that I have to modify the code on server side like the following:

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

Without touching the android code, the server can recieve and work on json data I sent now.

The problem is there is no way I can modify the code on the actual server.. So any idea why the $_POST not getting p


回答1:


You are sending data in json format, but not in $_POST array that's why $_POST is empty. If you cannot change server side code, then you may try out my HttpConnection class . Hope this will work.

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();
    }
}

Make post request by calling sendRequest method.You have to just pass the link, and the data to send with HashMap.



来源:https://stackoverflow.com/questions/33522025/android-how-can-i-communicate-with-php-server-using-httpurlconnection-post-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!