且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-17 09:24:02

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