HttpClient

package com.sytu.jthink.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class HttpUtils {
 // 基础URL
 public static final String BASE_URL = "http://192.168.137.1:8080/WirelessOrderDishes/";

 // 发送Get请求,获得响应查询结果
 public static JSONObject PostServer(String url, JSONObject json)
   throws JSONException, ClientProtocolException, IOException {
  // 定义结果JSON
  JSONObject result = new JSONObject();
  // 获得HttpPost对象
  HttpPost request = new HttpPost();
  request = new HttpPost(url);

  // 发送请求
  final List<NameValuePair> params = new ArrayList<NameValuePair>();
  NameValuePair nameValuePair = new BasicNameValuePair("json",
    json.toString());
  params.add(nameValuePair);
  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
  request.setEntity(entity);
  System.out.println(json);

  HttpResponse httpResponse = new DefaultHttpClient().execute(request);
  // 判断状态是否正常
  if (httpResponse.getStatusLine().getStatusCode() != 200) {
   // 获得响应
   result.put("result", "网络异常");
   return result;
  }
  // 得到应答的字符串,这也是一个 JSON 格式保存的数据
  String retSrc = EntityUtils.toString(httpResponse.getEntity());
  String strTemp = retSrc.replaceAll("\\\\", "");
  // 生成 JSON 对象
  result = new JSONObject(strTemp.substring(1, strTemp.length() - 1));
  System.out.println(result);
  return result;
 }
}

 

 

 

public void upDateData(Context context) {
  String url = HttpUtils.BASE_URL + "dataAjax/updateData.action";
  try {
   result = HttpUtils.PostServer(url, json);
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (JSONException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  try {
   dishAjaxBeans = JsonUtils.parseDishFromJson(result
     .getString("dishAjaxBeans"));
   boardAjaxBeans = JsonUtils.parseBoardFromJson(result
     .getString("boardAjaxBeans"));

  } catch (JSONException e) {
   e.printStackTrace();
  }

  // 开始更新数据库
  // 首先删除数据库
  DatabaseHelper dbHelper = new DatabaseHelper(context, "ordersystem");
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  db.delete("t_board", null, null);
  db.delete("t_dishes", null, null);
  dbHelper.close();
  db.close();

  // 更新数据
  update(context);
 }

你可能感兴趣的:(json post get)