如何使用Android在Request上发送JSON对象?

And*_*Dev 115 post android json httprequest

我想发送以下JSON文本

{"Email":"aaa@tbbb.com","Password":"123456"}
Run Code Online (Sandbox Code Playgroud)

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

我怎么能从android做到这一点?有哪些步骤,例如创建请求对象,设置内容标题等.

Pri*_*han 155

如果您使用Apache HTTP Client,则可以轻松地从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();      
    }
Run Code Online (Sandbox Code Playgroud)

您还可以使用Google Gson发送和检索JSON.


dma*_*oni 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);
Run Code Online (Sandbox Code Playgroud)

  • postMessage是一个JSON对象吗? (21认同)

Sac*_*ani 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) {
    }
}
Run Code Online (Sandbox Code Playgroud)


vik*_*koo 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;
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 8

Android链接下面有一个非常好的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);
    }
});
Run Code Online (Sandbox Code Playgroud)

要发送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);
Run Code Online (Sandbox Code Playgroud)

它都是异步的,适用于Android,可以安全地从UI线程调用.responseHandler将在您创建它的同一个线程上运行(通常是您的UI线程).它甚至有一个用于JSON的内置共振哈德勒,但我更喜欢使用谷歌gson.