Android 如何发送Json对象?

Android 如何发送Json对象?,android,json,http,Android,Json,Http,我真的是android的新手,所以谁能帮我解决我的问题呢…这里是:我使用两个自动完成的文本视图作为“用户名”和“密码”,所以这里我需要将用户名和密码作为JSon对象发送给HTTP请求。现在我如何在JSon对象中绑定用户名和密码。非常感谢您的帮助。请试用此代码 Button show_data; JSONObject my_json_obj; String path,firstname,lastname; path = "http://192.168.101.123:255/services/se

我真的是android的新手,所以谁能帮我解决我的问题呢…这里是:我使用两个自动完成的文本视图作为“用户名”和“密码”,所以这里我需要将用户名和密码作为JSon对象发送给HTTP请求。现在我如何在JSon对象中绑定用户名和密码。非常感谢您的帮助。请试用此代码

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

您可以使用将Json对象发送到服务器

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

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

}
公共类HttpClient{
私有静态最终字符串TAG=“HttpClient”;
公共静态JSONObject SendHttpPost(字符串URL,JSONObject JSONObject Send){
试一试{
DefaultHttpClient httpclient=新的DefaultHttpClient();
HttpPost httpPostRequest=新的HttpPost(URL);
Stringse;
se=新的StringEntity(jsonObjSend.toString());
//设置HTTP参数
httpPostRequest.setEntity(se);
setHeader(“接受”、“应用程序/json”);
setHeader(“内容类型”、“应用程序/json”);
httpPostRequest.setHeader(“接受编码”、“gzip”);//仅当要使用gzip压缩时才设置此参数
long t=System.currentTimeMillis();
HttpResponse response=(HttpResponse)httpclient.execute(httpPostRequest);
Log.i(标记,“HTTPResponse在[”+(System.currentTimeMillis()-t)+“ms]”中接收;
//获取响应实体(->数据):
HttpEntity=response.getEntity();
如果(实体!=null){
//阅读内容流
InputStream instream=entity.getContent();
Header contentEncoding=response.getFirstHeader(“内容编码”);
if(contentEncoding!=null&&contentEncoding.getValue().equalsIgnoreCase(“gzip”)){
流入=新的GZIPInputStream(流入);
}
//将内容流转换为字符串
字符串结果字符串=convertStreamToString(流内);
流内关闭();
resultString=resultString.substring(1,resultString.length()-1);//删除包装“[”和“]”
//将字符串转换为JSONObject
JSONObject JSONObjectRecv=新的JSONObject(resultString);
//接收到的JSON对象的原始调试输出:
Log.i(标记“\n”+jsonObjRecv.toString()+”\n”);
返回jsonObjRecv;
} 
}
捕获(例外e)
{
//有关HTTP异常处理的更多信息,请参见另一教程。
//现在我们只打印堆栈跟踪。
e、 printStackTrace();
}
返回null;
}
私有静态字符串convertStreamToString(InputStream为){
/*
*要将InputStream转换为字符串,我们使用BufferedReader.readLine()命令
*我们迭代直到BufferedReader返回null,这意味着
*没有更多的数据可读取。每行都将附加到StringBuilder
*并作为字符串返回。
* 
*(c)公共领域:http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
*/
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
}