/** * Gson解析对象为Json字符串 */ ParamsModel dataModel = new ParamsModel(); dataModel.setAccount("admin"); dataModel.setPassword("admin123");
Gson gson2 = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); String gsonString = gson2.toJson(model);
/** * 解析二 */ HashMap<String, String> params = new HashMap<>(); params.put("key1", "value1"); params.put("key2", "这里是需要提交的json格式数据"); params.put("key3", "也可以使用三方工具将对象转成json字符串"); params.put("key4", "其实你怎么高兴怎么写都行"); JSONObject jsonObject = new JSONObject(params); String strJson = jsonObject.toString();
/** * post请求 * @param json */ public void returnNet(final String json){ new Thread(new Runnable() { @Override public void run() { HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(GlobalConstant.API_HOST); post.setHeader("Content-type", "application/json"); StringEntity postingString = null;// json传递 try { postingString = new StringEntity(json); post.setEntity(postingString); HttpResponse response = httpClient.execute(post); System.out.println(post.toString()); if(response.getStatusLine().getStatusCode()==200){ HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); System.out.println(result); JSONObject json = JSON.parseObject(result); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); }
/** * get请求 */ public void returnGet(){ new Thread(new Runnable() { @Override public void run() { String uriAPI = "https://www.hao123.com/"; String result= ""; // HttpGet httpRequst = new HttpGet(URI uri); // HttpGet httpRequst = new HttpGet(String uri); // 创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。 HttpGet httpRequst = new HttpGet(uriAPI); // new DefaultHttpClient().execute(HttpUriRequst requst); try { //使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);//其中HttpGet是HttpUriRequst的子类 System.out.println(httpRequst.toString()); if(httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity);//取出应答字符串 // 一般来说都要删除多余的字符 result.replaceAll("\r", "");//去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格 Log.e("==result==",result.toString()); JSONObject json = JSON.parseObject(result); } else{ httpRequst.abort(); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); result = e.getMessage().toString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); result = e.getMessage().toString(); } } }).start(); }