第一种:

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:\n" + 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:\n" + 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" />

android http json请求3种不同写法的更多相关文章

  1. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

  2. 转--Android按钮单击事件的四种常用写法总结

    这篇文章主要介绍了Android按钮单击事件的四种常用写法总结,比较了常见的四种写法的优劣,有不错的参考借鉴价值,需要的朋友可以参考下     很多学习Android程序设计的人都会发现每个人对代码的 ...

  3. android通过httpClient请求获取JSON数据并且解析

    使用.net创建一个ashx文件,并response.write  json格式 public void ProcessRequest(HttpContext context) { context.R ...

  4. android http post 请求与 json字符串

    一.目标 android客户端发送一个json格式的http的请求,期望得到服务端的一个json反馈. 1. 客户端发送的json格式为: {"data" : "valu ...

  5. Android按钮单击事件的四种常用写法

    这篇文章主要介绍了Android按钮单击事件的四种常用写法总结,比较了常见的四种写法的优劣,有不错的参考借鉴价值,需要的朋友可以参考下 很多学习Android程序设计的人都会发现每个人对代码的写法都有 ...

  6. Android框架Volley使用:Json请求实现

    首先我们在项目中导入这个框架: implementation 'com.mcxiaoke.volley:library:1.0.19' 在AndroidManifest文件当中添加网络权限: < ...

  7. android基础---->JSON数据的解析

    上篇博客,我们谈到了XML两种常用的解析技术,详细可以参见我的博客(android基础---->XMl数据的解析).网络传输另外一种数据格式JSON就是我们今天要讲的,它是比XML体积更小的数据 ...

  8. Android okHttp网络请求之缓存控制Cache-Control

    前言: 前面的学习基本上已经可以完成开发需求了,但是在项目中有时会遇到对请求做个缓存,当没网络的时候优先加载本地缓存,基于这个需求我们来学习一直okHttp的Cache-Control. okHttp ...

  9. Android okHttp网络请求之Retrofit+Okhttp+RxJava组合

    前言: 通过上面的学习,我们不难发现单纯使用okHttp来作为网络库还是多多少少有那么一点点不太方便,而且还需自己来管理接口,对于接口的使用的是哪种请求方式也不能一目了然,出于这个目的接下来学习一下R ...

随机推荐

  1. DIOCP3 - 关于接收数据

    DIOCP3支持两种方式接收数据,   第一种是原始的流数据, 最通用的一种方式,客户端发啥,这边就收到啥.需要自己处理粘包问题. 可以在TCilentContext或者TIocpTcpServer的 ...

  2. 安装Python2.7出现configure: error: no acceptable C compiler found in $PATH错误

    安装Python2.7出现configure: error: no acceptable C compiler found in $PATH错误 安装步骤: 安装依赖 yum groupinstall ...

  3. Windows下搭建Android NDK开发环境及命令行编译

    首先说明本文内的相关安装操作参考<Pro Android C++ with the NDK>一书. 安装 Windows搭建Android NDK开发环境需要安装如下部分(同时需要配置对应 ...

  4. Linux内核分析:recv、recvfrom、recvmsg函数实现

    先看一下这三个函数的声明: #include <sys/types.h> #include <sys/socket.h> ssize_t recv(int sockfd, vo ...

  5. Python3.5爬取豆瓣电视剧数据并且同步到mysql中

    #!/usr/local/bin/python # -*- coding: utf-8 -*- # Python: 3.5 # Author: zhenghai.zhang@xxx.com # Pro ...

  6. java多线程14 :wait()和notify()/notifyAll()

    轮询 线程本身是操作系统中独立的个体,但是线程与线程之间不是独立的个体,因为它们彼此之间要相互通信和协作. 想像一个场景,A线程做int型变量i的累加操作,B线程等待i到了10000就打印出i,怎么处 ...

  7. tf.truncated_normal

    tf.truncated_normal truncated_normal( shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name ...

  8. 基于html5背景图片自适应代码

    基于html5背景图片自适应代码是一款背景不随滚动条滚动,会根据分辨率不同自动匹配对应的背景图片.效果图如下: 在线预览   源码下载 实现的代码. css代码: .jawbone-hero .jaw ...

  9. WCF终结点——终结点地址(EndpointAddress)

    终结点的地址的Uri属性作为终结点地址的唯一标示. 包括客户端终结点和服务端终结点. 一.服务端终结点: 服务端的终结点通过宿主的添加方法暴露出来,从而成为可以调用的资源. 下面是将服务绑定到宿主的代 ...

  10. Android ListView的使用(三)

    前两节关于ListView的,已经使用了ArrayAdapter,SimpleAdapter了,两个比较基本的适配器 这里来用一个用的最多的一个适配器BaseAdapter. 还是先上效果图.大概和微 ...