如何在Android中通过请求发送JSON对象?

116

我想发送以下JSON文本

{"Email":"aaa@tbbb.com","Password":"123456"}

如何从Android端向Web服务发送请求并读取响应。我知道如何读取JSON,但问题是上述的JSON对象必须在变量名jason中被发送。

我该如何实现呢?需要哪些步骤,例如创建请求对象、设置内容头等等。

8个回答

155

如果您使用Apache HTTP客户端,从Android发送JSON对象非常容易。这里是一个代码示例,演示如何实现。您应该为网络活动创建一个新的线程,以避免锁定UI线程。

    protected void sendJson(final String email, final String pwd) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                    HttpPost post = new HttpPost(URL);
                    json.put("email", email);
                    json.put("password", pwd);
                    StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */
                    if(response!=null){
                        InputStream in = response.getEntity().getContent(); //Get the data in the entity
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                    createDialog("Error", "Cannot Estabilish Connection");
                }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();      
    }

您也可以使用Google Gson来发送和获取JSON数据。

你好,可能服务器要求我设置一个名为JSON的头,并将JSON内容放在该头中,这是否可能?我发送的URL如下: HttpPost post = new HttpPost("http://www.abc.com/xyz/usersgetuserdetails");但是它显示无效请求错误。代码的其余部分相同。另外,json = header = new JSONObject()是什么意思? - AndroidDev
我不确定服务器期望什么样的请求。至于这个“json = header = new JSONObject();”,它只是创建了两个JSON对象。 - Primal Pappachan
@primpop - 你能否提供一个简单的PHP脚本来配合这个吗?我尝试着实现你的代码,但是我无论如何都只能发送NULL。 - kubiej21
你可以像这样将输入流(在此处是一个对象)转换为字符串: StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String theString = writer.toString(); - Yekmer Simsek

97

Android没有用于发送和接收HTTP的特殊代码,可以使用标准的Java代码。我建议使用随Android一起提供的Apache HTTP客户端。这是我用于发送HTTP POST的代码片段。

我不明白将对象发送到名为“jason”的变量中与任何事情有关。如果你不确定服务器需要什么格式,考虑编写一个测试程序,向服务器发送各种字符串,直到你知道它需要的格式为止。

int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
    postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);

目前已经过时了,非常遗憾。 :( - tony gil

35
public void postData(String url,JSONObject obj) {
    // Create a new HttpClient and Post Header

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient(myParams );
    String json=obj.toString();

    try {

        HttpPost httppost = new HttpPost(url.toString());
        httppost.setHeader("Content-type", "application/json");

        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se); 

        HttpResponse response = httpclient.execute(httppost);
        String temp = EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);


    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
}

19

HttpPost在Android Api Level 22中已被弃用。因此,请改用HttpUrlConnection

public static String makeRequest(String uri, String json) {
    HttpURLConnection urlConnection;
    String url;
    String data = json;
    String result = null;
    try {
        //Connect 
        urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();

        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

8
以下链接提供了一个非常好用的Android HTTP库:

https://github.com/square/okhttp

http://loopj.com/android-async-http/

简单请求非常容易:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});

发送JSON(感谢https://github.com/loopj/android-async-http/issues/125上的`voidberg'):

// params is a JSONObject
StringEntity se = null;
try {
    se = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
    // handle exceptions properly!
}
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

client.post(null, "www.example.com/objects", se, "application/json", responseHandler);

所有操作都是异步的,与Android兼容,并且可以安全地从您的UI线程调用。响应处理程序将在您创建它的线程上运行(通常是您的UI线程)。它甚至还配备了一个内置的JSON响应处理程序,但我更喜欢使用Google Gson。


你知道这个程序的最低SDK是多少吗? - Esko918
如果它不是GUI,我会感到惊讶它是否有最低要求。为什么不试一下并发布你的发现呢? - Alex
1
我决定使用本地库。关于这方面有更多的信息,因为我对Android还比较新。我其实是一个iOS开发者。这样做更好,因为我正在阅读所有文档,而不仅仅是插入和播放别人的代码。谢谢。 - Esko918

3

现在由于 HttpClient 已被弃用,当前的工作代码是使用 HttpUrlConnection 建立连接并从连接中读取和写入数据。但我更喜欢使用Volley库。这个库来自于 Android AOSP。我发现它非常容易使用,可以轻松制作 JsonObjectRequestJsonArrayRequest


2

这个非常简单。使用OkHttpLibrary。

创建你的json。

JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);

并像这样发送它。
OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .url(url)
            .post(requestObject.toString())
            .build();

okhttp3.Response response = client.newCall(request).execute();

点赞指向了okhttp,这是一个有用的库,但是给出的代码并没有太大帮助。例如,RequestBody.create()传递了哪些参数?请参阅此链接以获取更多详细信息:http://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html - Dabbler

0
public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
    JSONArray array;
    @Override
    protected JSONArray doInBackground(Void... params) {

        try {
            commonurl cu = new commonurl();
            String u = cu.geturl("tempshowusermain.php");
            URL url =new URL(u);
          //  URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("lid",lid);


            DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            outputStream.write(jsonObject.toString().getBytes("UTF-8"));

            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                StringBuffer stringBuffer = new StringBuffer();
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                object =  new JSONObject(stringBuffer.toString());
             //   array = new JSONArray(stringBuffer.toString());
                array = object.getJSONArray("response");

            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return array;


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();



    }

    @Override
    protected void onPostExecute(JSONArray array) {
        super.onPostExecute(array);
        try {
            for (int x = 0; x < array.length(); x++) {

                object = array.getJSONObject(x);
                ComonUserView commUserView=new ComonUserView();//  commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
                //pidArray.add(jsonObject2.getString("pid").toString());

                commUserView.setLid(object.get("lid").toString());
                commUserView.setUname(object.get("uname").toString());
                commUserView.setAboutme(object.get("aboutme").toString());
                commUserView.setHeight(object.get("height").toString());
                commUserView.setAge(object.get("age").toString());
                commUserView.setWeight(object.get("weight").toString());
                commUserView.setBodytype(object.get("bodytype").toString());
                commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
                commUserView.setImagepath(object.get("imagepath").toString());
                commUserView.setDistance(object.get("distance").toString());
                commUserView.setLookingfor(object.get("lookingfor").toString());
                commUserView.setStatus(object.get("status").toString());

                cm.add(commUserView);
            }
            custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
          gridusername.setAdapter(custuserprof);
            //  listusername.setAdapter(custuserprof);
            } catch (Exception e) {

                e.printStackTrace();
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接