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:\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种不同写法的更多相关文章
- Android okHttp网络请求之Json解析
前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...
- 转--Android按钮单击事件的四种常用写法总结
这篇文章主要介绍了Android按钮单击事件的四种常用写法总结,比较了常见的四种写法的优劣,有不错的参考借鉴价值,需要的朋友可以参考下 很多学习Android程序设计的人都会发现每个人对代码的 ...
- android通过httpClient请求获取JSON数据并且解析
使用.net创建一个ashx文件,并response.write json格式 public void ProcessRequest(HttpContext context) { context.R ...
- android http post 请求与 json字符串
一.目标 android客户端发送一个json格式的http的请求,期望得到服务端的一个json反馈. 1. 客户端发送的json格式为: {"data" : "valu ...
- Android按钮单击事件的四种常用写法
这篇文章主要介绍了Android按钮单击事件的四种常用写法总结,比较了常见的四种写法的优劣,有不错的参考借鉴价值,需要的朋友可以参考下 很多学习Android程序设计的人都会发现每个人对代码的写法都有 ...
- Android框架Volley使用:Json请求实现
首先我们在项目中导入这个框架: implementation 'com.mcxiaoke.volley:library:1.0.19' 在AndroidManifest文件当中添加网络权限: < ...
- android基础---->JSON数据的解析
上篇博客,我们谈到了XML两种常用的解析技术,详细可以参见我的博客(android基础---->XMl数据的解析).网络传输另外一种数据格式JSON就是我们今天要讲的,它是比XML体积更小的数据 ...
- Android okHttp网络请求之缓存控制Cache-Control
前言: 前面的学习基本上已经可以完成开发需求了,但是在项目中有时会遇到对请求做个缓存,当没网络的时候优先加载本地缓存,基于这个需求我们来学习一直okHttp的Cache-Control. okHttp ...
- Android okHttp网络请求之Retrofit+Okhttp+RxJava组合
前言: 通过上面的学习,我们不难发现单纯使用okHttp来作为网络库还是多多少少有那么一点点不太方便,而且还需自己来管理接口,对于接口的使用的是哪种请求方式也不能一目了然,出于这个目的接下来学习一下R ...
随机推荐
- Android,XML解析
XML解析三种方式 DOM 通用性强,它会将XML文件的所有内容读取到内存中,然后允许您使用DOM API遍历XML树.检索所需的数据: 简单直观,但需要将文档读取到内存,并不太适合移动设备: SAX ...
- win10下安装redis 服务
Window 下安装 下载地址:https://github.com/MSOpenTech/redis/releases Redis 支持 32 位和 64 位.这个需要根据你系统平台的实际情况选择, ...
- 【Tensorflow】设置显存自适应,显存比例
用惯了theano.再用tensoflow发现一运行显存就满载了,吓得我吃了一个苹果. 用天朝搜索引擎毛都搜不到,于是FQ找了下问题的解决方法,原来有两种 按比例 config = tf.Config ...
- “一键制作启动u盘失败”的主要原因是什么?
一键制作启动u盘失败的主要原因是什么?今天u启动小编就和大家一起来分析原因并寻求答案吧! 原因分析: 1.u盘内有文件正在运行或者是打开: 2.u盘自身的质量问题: 3.最主要的原 ...
- Python如何下载文件
转载自:http://www.codecho.com/how-to-download-a-file-in-python/ 利用程序自己编写下载文件挺有意思的.Python中最流行的方法就是通过Http ...
- JAVA-JSP内置对象之pageContext对象取得不同范围属性
相关资料:<21天学通Java Web开发> pageContext对象取得不同范围属性 pageContextDemo.jsp <%@ page language="ja ...
- JD 题目1040:Prime Number (筛法求素数)
OJ题目:click here~~ 题目分析:输出第k个素数 贴这么简单的题目,目的不清纯 用筛法求素数的基本思想是:把从1開始的.某一范围内的正整数从小到大顺序排列, 1不是素数,首先把它筛掉.剩下 ...
- [转载]WPF控件拖动
这篇博文总结下WPF中的拖动,文章内容主要包括: 1.拖动窗口 2.拖动控件 Using Visual Studio 2.1thumb控件 2.2Drag.Drop(不连续,没有中间动画) 2.3拖动 ...
- Python 读取数据
将一个文件夹下面的图像和对应的pts读进来,然后把pts文件里面的数据读入一个数组,然后画到图像上: # -*- coding:utf- -*- """ 测试数据样例 & ...
- js 日期格式化函数
直接上代码: // 日期格式化函数 // yyyy/MM/dd hh:mm:ss SSS ⇒ "2017/05/16 09:24:20 850" //"yyyy/M/d ...