我想发送以下JSON文本
{"Email":"aaa@tbbb.com","Password":"123456"}
发送到web服务并读取响应。我知道如何阅读JSON。问题是上面的JSON对象必须在名为jason
的变量中发送。
我怎样才能在android上做到这一点?创建请求对象、设置内容头部等步骤是什么?
发布于 2010-06-12 10:17:27
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);
发布于 2010-06-12 15:40:05
如果使用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。
发布于 2012-02-22 14:32:48
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) {
}
}
https://stackoverflow.com/questions/3027066
复制相似问题