如何使用Android通过Request发送JSON对象?


115

我想发送以下JSON文本

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

到Web服务并读取响应。我知道如何读取JSON。问题是上述JSON对象必须以变量名发送jason

我该如何从android做到这一点?创建请求对象,设置内容标头等步骤是什么。

Answers:


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

21
postMessage是JSON对象吗?
AndroidDev 2010年

postMessage未定义
Raptor'1

超时是什么时间?
Lion789

如果传递多个字符串怎么办?例如postMessage2.toString()。getBytes(“ UTF8”)
Mayur R. Amipara

建议将POJO转换为Json字符串?
tgkprog

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内容放入该标头中?我将网址发送为HttpPost post = new HttpPost(“ abc.com/xyz/usersgetuserdetails”); 但是它说无效请求错误。代码的难忘之处是相同的。其次json = header = new JSONObject(); 这是
怎么回事

我不确定服务器需要什么样的请求。至于这个'json = header = new JSONObject(); '它只是创建2个json对象。
Primal Pappachan

@primpop-您是否有可能提供一个简单的php脚本来解决这个问题?我尝试实现您的代码,但是我一生无法获得除NULL之外的任何其他功能。
kubiej21'4

您可以像这样的字符串从inputsputstream(在此处的对象中)获取输出,例如:StringWriter writer = new StringWriter(); IOUtils.copy(in,writer,“ UTF-8”); 字符串theString = writer.toString();
Yekmer Simsek

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

我已经将json对象发布到ASP.Net mvc服务器。如何在ASP.Net服务器中查询相同的json字符串?
Karthick

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

1
公认的答案已贬值,这种方法更好
CoderBC

8

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

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线程安全地进行调用。responseHandler将在您从其创建的同一线程上运行(通常是您的UI线程)。它甚至具有用于JSON的内置resonseHandler,但我更喜欢使用Google gson。


您知道运行此代码的最低SDK吗?
Esko918

如果它不是GUI,那么如果它有一个最小值,我会感到惊讶。为什么不尝试一下并发布您的发现。
亚历克斯(Alex)

1
好吧,我决定改用本机库。有更多关于那的信息,因为即时消息对android来说还很新。我真的是iOS开发人员。由于即时通讯可以读取所有文档,而不仅仅是插入并玩别人的代码,因此效果更好。不过
Esko918 2015年

3

现在,由于HttpClient不推荐使用,因此当前的工作代码是使用HttpUrlConnection来创建连接并写入和从连接中读取数据。但是我更喜欢使用排球。该库来自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()的参数是什么?有关更多详细信息,请参见此
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();
        }
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.