如何通过Android请求发送JSON对象?我想发送以下JSON文本{"Email":"aaa@tbbb.com","Password":"123456"}并读取响应。我知道怎么读JSON。问题是上面的JSON对象必须以变量名发送jason.我怎样才能在Android上做到这一点呢?创建请求对象、设置内容标题等步骤有哪些。
3 回答
![?](http://img1.sycdn.imooc.com/54584cfb0001308402200220-100-100.jpg)
慕村9548890
TA贡献1884条经验 获得超4个赞
int TIMEOUT_MILLISEC = 10000; // = 10 secondsString 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);
![?](http://img1.sycdn.imooc.com/533e4c5600017c5b02010200-100-100.jpg)
慕标5832272
TA贡献1966条经验 获得超4个赞
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(); }
![?](http://img1.sycdn.imooc.com/54586431000103bb02200220-100-100.jpg)
Cats萌萌
TA贡献1805条经验 获得超9个赞
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) { }}
- 3 回答
- 0 关注
- 818 浏览
添加回答
举报
0/150
提交
取消