如何发送Json对象?

时间:2011-04-30 10:54:25

标签: android json http

我是Android中的新蜜蜂,所以有人可以帮我解决我的问题......这里是:我使用两个AutoCompletedTextView作为“用户名”和“密码”,所以在这里我需要发送用户名和密码作为HTTP请求的JSon对象。现在如何在Json对象中绑定用户名和密码。任何帮助将非常感谢谢谢

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

试试这段代码

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

答案 2 :(得分:0)

您可以使用

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

}