zoukankan      html  css  js  c++  java
  • android http json请求3种不同写法

    第一种:

      public static String invoke() {
            String result = null;
            try {
                 final String url = "http://192.168.1.104:180/";

                HttpPost httpPost = new HttpPost(url);
                DefaultHttpClient httpClient = new DefaultHttpClient();

                //基本身份验证
                BasicCredentialsProvider bcp = new BasicCredentialsProvider();
                String userName = "liudong";
                String password = "123";
                bcp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        userName, password));
                httpClient.setCredentialsProvider(bcp);

                HttpResponse httpResponse = httpClient.execute(httpPost);

                StringBuilder builder = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        httpResponse.getEntity().getContent()));
                for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                    builder.append(s);
                }
                result = builder.toString();
                Log.d(TAG, "result is ( " + result + " )");
            } catch (Exception e) {
                Log.e(TAG, e.toString());
            }
            Log.d(TAG, "over");
            return result;
        }

    第二种:

    public static String SendRequest(String adress_Http, String strJson) {

      String returnLine = "";
      try {

       System.out.println("**************开始http通讯**************");
       System.out.println("**************调用的接口地址为**************" + adress_Http);
       System.out.println("**************请求发送的数据为**************" + strJson);
       URL my_url = new URL(adress_Http);
       HttpURLConnection connection = (HttpURLConnection) my_url.openConnection();
       connection.setDoOutput(true);

       connection.setDoInput(true);

       connection.setRequestMethod("POST");
       
       connection.setUseCaches(false);
       
       connection.setInstanceFollowRedirects(true);
       
       connection.setRequestProperty("Content-Type", "application/json");
       
       connection.connect();
       DataOutputStream out = new DataOutputStream(connection
         .getOutputStream());
       
       byte[] content = strJson.getBytes("utf-8");
       
       out.write(content, 0, content.length);
       out.flush();
       out.close(); // flush and close

       BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

       //StringBuilder builder = new StringBuilder();

       String line = "";

       System.out.println("Contents of post request start");

       while ((line = reader.readLine()) != null) {
        // line = new String(line.getBytes(), "utf-8");
        returnLine += line;
        
        System.out.println(line);
        
       }

       System.out.println("Contents of post request ends");
       
       reader.close();
       connection.disconnect();
       System.out.println("========返回的结果的为========" + returnLine);

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

      return returnLine;

     }

    第三种:

    protected DAOReturnObject doInBackground(JSONObject... jsonObjects) {
      DAOReturnObject returnObject;
      try {
       publishProgress("处理中...");
       String serverUrl = "http://130.251.10.195:8091";//MServerSettingInfoDAO.getInstance().getUrl();
       String url = serverUrl+"/customerLogin";
       HttpPost httpPost = new HttpPost(url);
       Log.i("URL", url);
       ByteArrayEntity arrayEntity = null;
       byte[] jsonByte = null;
       try {
        jsonByte = jsonObjects[0].toString().getBytes(DEFAULT_ENCODING);
        arrayEntity = new ByteArrayEntity(jsonByte); 
       } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new Exception("数据打包出错!");
       }
       Log.d("M-Client", "request JSON: " + new String(jsonByte, DEFAULT_ENCODING ));
       httpPost.setEntity(arrayEntity);
       httpPost.setHeader("Accept", "application/json");
       httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
       HttpResponse httpResponse;
       byte[] responseByte;
       String responseStr;
       try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        // 设置COOKIES
        HttpContext localContext = new BasicHttpContext();
        httpResponse = httpclient.execute(httpPost, localContext);
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
         throw new Exception("接收数据出错:" + httpResponse.getStatusLine().toString());
        }
        responseByte = EntityUtils.toByteArray(httpResponse.getEntity());
        //写缓存
    //    MServerSettingInfoDAO.getInstance().setStreamInfo(MClientFunction.getFileDir(), 
    //      responseByte.length, "res");
    //    MClientFunction.setResCurrentStream(responseByte.length);
        
        Log.d("M-Client", "response JSON: " + new String(responseByte, 0, responseByte.length, DEFAULT_ENCODING));
        responseStr = new String(responseByte, 0, responseByte.length, DEFAULT_ENCODING);
       } catch (ClientProtocolException e) {
        Log.e("M-Client", "接收数据出错!", e);
        throw new Exception("接收数据出错:" + e.getMessage(), e);
       } catch (IOException e) {
        Log.e("M-Client", "接收数据出错!", e);
        throw new Exception("接收数据出错:" + e.getMessage(), e);
       }
       try {
        Map<String, Object> responseMap = (Map<String, Object>)JsonUtil.json2Object(new JSONObject(responseStr));
        returnObject = new DAOReturnObject(Integer.parseInt((String) responseMap.get("code")), (String) responseMap.get("msg"), responseMap.get("res"));
       } catch (JSONException e) {
        Log.e("M-Client", "接收数据出错!", e);
        throw new Exception("接收数据出错:" + e.getMessage(), e);
       }
      } catch (Exception e) {
       return new DAOReturnObject(99, e.getMessage(), null);
      }
      return returnObject;
     }

    记得加上访问权限:<uses-permission android:name="android.permission.INTERNET" />

  • 相关阅读:
    JS预编译
    伪元素、伪类和选择器之间的区别
    js中== 和 != 的转换规则
    js数据类型的转换
    数组习题
    document语句以及html()等方法
    第十一章 以太网交换机工作原理
    第一章 架构基础介绍
    Linux常规练习题(二)参考答案
    第三十四章 Linux常规练习题(一)参考答案
  • 原文地址:https://www.cnblogs.com/kobe8/p/4030455.html
Copyright © 2011-2022 走看看