Android 如何用HttpClient 以Post方式提交数据并添加http头信息
Android 如何 post json格式的数据,并附加http头,接受返回数据,请看下面的代码:
- private void HttpPostData() {
- try {
- HttpClient httpclient = new DefaultHttpClient();
- String uri = "http://www.yourweb.com";
- HttpPost httppost = new HttpPost(uri);
- //添加http头信息
- httppost.addHeader("Authorization", "your token"); //认证token
- httppost.addHeader("Content-Type", "application/json");
- httppost.addHeader("User-Agent", "imgfornote");
- //http post的json数据格式: {"name": "your name","parentId": "id_of_parent"}
- JSONObject obj = new JSONObject();
- obj.put("name", "your name");
- obj.put("parentId", "your parentid");
- httppost.setEntity(new StringEntity(obj.toString()));
- HttpResponse response;
- response = httpclient.execute(httppost);
- //检验状态码,如果成功接收数据
- int code = response.getStatusLine().getStatusCode();
- if (code == 200) {
- String rev = EntityUtils.toString(response.getEntity());//返回json格式: {"id": "27JpL~j4vsL0LX00E00005","version": "abc"}
- obj = new JSONObject(rev);
- String id = obj.getString("id");
- String version = obj.getString("version");
- }
- } catch (ClientProtocolException e) {
- } catch (IOException e) {
- } catch (Exception e) {
- }
- }
主要用到的类有:org.apache.http.client.HttpClient 、org.apache.http.client.methods.HttpPost 和 org.json.JSONObject
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20