如何使用 Android 通过 Request 发送 JSON 对象? [英] How to send a JSON object over Request with Android?

查看:74
本文介绍了如何使用 Android 通过 Request 发送 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发送以下 JSON 文本

I want to send the following JSON text

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

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

to a web service and read the response. I know to how to read JSON. The problem is that the above JSON object must be sent in a variable name jason.

我怎样才能从安卓上做到这一点?创建请求对象、设置内容头等步骤是什么

How can I do this from android? What are the steps such as creating request object, setting content headers, etc.

推荐答案

Android 没有专门的发送和接收 HTTP 代码,你可以使用标准的 Java 代码.我建议使用 Android 附带的 Apache HTTP 客户端.这是我用来发送 HTTP POST 的一段代码.

Android doesn't have special code for sending and receiving HTTP, you can use standard Java code. I'd recommend using the Apache HTTP client, which comes with Android. Here's a snippet of code I used to send an HTTP POST.

我不明白在名为jason"的变量中发送对象有什么关系.如果您不确定服务器到底想要什么,请考虑编写一个测试程序将各种字符串发送到服务器,直到您知道它需要采用什么格式.

I don't understand what sending the object in a variable named "jason" has to do with anything. If you're not sure what exactly the server wants, consider writing a test program to send various strings to the server until you know what format it needs to be in.

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

这篇关于如何使用 Android 通过 Request 发送 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆