Как отправить объект Json? - PullRequest
0 голосов
/ 30 апреля 2011

Я действительно новая пчела в Android, поэтому кто-нибудь может, пожалуйста, помочь мне в моей проблеме ... вот: я использую два AutoCompletedTextView в качестве «имени пользователя» и «пароля», поэтому здесь мне нужно отправить имя пользователя и паролькак JSon Object для HTTP-запроса. Теперь, как связать имя пользователя и пароль в объекте Json.Любая помощь будет по достоинству оценена СПАСИБО

Ответы [ 3 ]

1 голос
/ 02 мая 2011

Попробуйте этот код

Button show_data;
JSONObject my_json_obj;
String path,firstname,lastname;
path = "http://192.168.101.123:255/services/services.php?id=9";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpEntity  entity;
HttpResponse response = null;
HttpURLConnection urlconn;
my_json_obj = new JSONObject();
try
{
    urlconn = (HttpURLConnection) new URL(path).openConnection();
    urlconn.setConnectTimeout(10000);
    urlconn.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(urlconn.getOutputStream(), "UTF-8");

my_json_obj.put("sUserName", "test2"); my_json_obj.put("sPassword", "123456");

writer.write(my_json_obj.toString()); writer.close();

if(true) { String temp; temp = WebRequestCall(my_json_obj); //Log.i("Reply", temp); }
1 голос
0 голосов
/ 01 марта 2013

Вы можете отправить объект Json на сервер, используя

JSONObject jsonObjRecv = HttpClient.SendHttpPost(URL, jsonObjSend);

и HttpClient class - это

public class HttpClient {
    private static final String TAG = "HttpClient";

    public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPostRequest = new HttpPost(URL);

            StringEntity se;
            se = new StringEntity(jsonObjSend.toString());

            // Set HTTP parameters
            httpPostRequest.setEntity(se);
            httpPostRequest.setHeader("Accept", "application/json");
            httpPostRequest.setHeader("Content-type", "application/json");
            httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

            long t = System.currentTimeMillis();
            HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
            Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

            // Get hold of the response entity (-> the data):
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // Read the content stream
                InputStream instream = entity.getContent();
                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    instream = new GZIPInputStream(instream);
                }

                // convert content stream to a String
                String resultString= convertStreamToString(instream);
                instream.close();
                resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

                // Transform the String into a JSONObject
                JSONObject jsonObjRecv = new JSONObject(resultString);
                // Raw DEBUG output of our received JSON object:
                Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

                return jsonObjRecv;
            } 

        }
        catch (Exception e)
        {
            // More about HTTP exception handling in another tutorial.
            // For now we just print the stack trace.
            e.printStackTrace();
        }
        return null;
    }


    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         * 
         * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...