HTTP请求与响应

HTTP请求包结构

例:

POST /meme.php/home/user/login HTTP/1.1
Host: 114.215.86.90
Cache-Control: no-cache
Postman-Token: bd243d6b-da03-902f-0a2c-8e9377f6f6ed
Content-Type: application/x-www-form-urlencoded tel=13637829200&password=123456

HTTP响应包结构

例:

HTTP/1.1 200 OK
Date: Sat, 02 Jan 2016 13:20:55 GMT
Server: Apache/2.4.6 (CentOS) PHP/5.6.14
X-Powered-By: PHP/5.6.14
Content-Length: 78
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8 {"status":202,"info":"\u6b64\u7528\u6237\u4e0d\u5b58\u5728\uff01","data":null}

Http请求方式

常用的是Post和Get

Get方式

在url中填写参数:http://xxxx.xx.com/xx.php?params1=value1&params2=value2

Post方式

参数是经过编码放在请求体中的。编码包括x-www-form-urlencoded 与 form-data

x-www-form-urlencoded的编码方式是这样: tel=13637829200&password=123456

form-data的编码方式是这样:

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="tel" 13637829200
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="password" 123456
----WebKitFormBoundary7MA4YWxkTrZu0gW

x-www-form-urlencoded只能传键值对,form-data可以传二进制

HttpClient & HttpURLConnection

HttpClient已被废弃

HttpURLConnection的用法

public class NetUtils {
public static String post(String url, String content) {
HttpURLConnection conn = null;
try {
// 创建一个URL对象
URL mURL = new URL(url);
// 调用URL的openConnection()方法,获取HttpURLConnection对象
conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("POST");// 设置请求方法为post
conn.setReadTimeout(5000);// 设置读取超时为5秒
conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容 // post请求的参数
String data = content;
// 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
out.write(data.getBytes());
out.flush();
out.close(); int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
if (responseCode == 200) { InputStream is = conn.getInputStream();
String response = getStringFromInputStream(is);
return response;
} else {
throw new NetworkErrorException("response status is "+responseCode);
} } catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();// 关闭连接
}
} return null;
} public static String get(String url) {
HttpURLConnection conn = null;
try {
// 利用string url构建URL对象
URL mURL = new URL(url);
conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(10000); int responseCode = conn.getResponseCode();
if (responseCode == 200) { InputStream is = conn.getInputStream();
String response = getStringFromInputStream(is);
return response;
} else {
throw new NetworkErrorException("response status is "+responseCode);
} } catch (Exception e) {
e.printStackTrace();
} finally { if (conn != null) {
conn.disconnect();
}
} return null;
} private static String getStringFromInputStream(InputStream is)
throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 模板代码 必须熟练
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
is.close();
String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
os.close();
return state;
}
}

添加网络权限:<uses-permission android:name="android.permission.INTERNET"/>

同步&异步

异步方式:

//在主线程new的Handler,就会在主线程进行后续处理。
private Handler handler = new Handler();
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
new Thread(new Runnable() {
@Override
public void run() {
//从网络获取数据
final String response = NetUtils.get("http://www.baidu.com");
//向Handler发送处理操作
handler.post(new Runnable() {
@Override
public void run() {
//在UI线程更新UI
textView.setText(response);
}
});
}
}).start();
}

参考文献:http://www.jianshu.com/p/3141d4e46240

Android网络请求的更多相关文章

  1. Android网络请求框架AsyncHttpClient实例详解(配合JSON解析调用接口)

    最近做项目要求使用到网络,想来想去选择了AsyncHttpClient框架开进行APP开发.在这里把我工作期间遇到的问题以及对AsyncHttpClient的使用经验做出相应总结,希望能对您的学习有所 ...

  2. xamarin android网络请求总结

    xamarin android中网络请求的框架非常多,在项目中使用的是第三方的一个网络请求框架restsharp,应该是github上.net网络请求最多star的框架,没有之一.这里就简单汇总了其他 ...

  3. Android 网络请求框架Retrofit

    Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的,OkHttp现在已经得到Google官方认可,大量的app都采用OkHttp ...

  4. Android 网络请求及数据处理

    Android 网络请求: 1.Volley   http://blog.csdn.net/t12x3456/article/details/9221611 2.Android-Async-Http  ...

  5. Android 网络请求Retrofit + RxJava

    一.背景 经常看到项目用Retrofit+RxJava+RxAndroid的框架,为了看懂项目的结构.现在来了解一下,Retrofit: Retrofit是Square 公司开发的一款正对Androi ...

  6. android 网络请求Ⅰ

    本章讲述在android开发中,常用的网络请求操作.网络请求利用android基本的HttpURLConnection连接URL和开源网络请求包AsyncHttpClient.本次网络请求以调取天气接 ...

  7. Android网络请求通信之Volley

    一.Volley简介 Volley网络框架是Google公司在2013年发布的一款Android平台上的网络请求通信库.以下是对Volley的简单归纳. Volley的优点: 使网络通信更快.更简单. ...

  8. android 网络请求库的比较

    源码请戳 一. 现有库和选择的库 HttpURLConnection:是Java中的标准类,是对Java中socket的封装. Httpclient:是Apache的开源框架,是对HttpURLCon ...

  9. 浅论Android网络请求库——android-async-http

    在iOS开发中有大名鼎鼎的ASIHttpRequest库,用来处理网络请求操作,今天要介绍的是一个在Android上同样强大的网络请求库android-async-http,目前非常火的应用Insta ...

  10. Android网络请求框架

    本篇主要介绍一下Android中经常用到的网络请求框架: 客户端网络请求,就是客户端发起网络请求,经过网络框架的特殊处理,让后将请求发送的服务器,服务器根据 请求的参数,返回客户端需要的数据,经过网络 ...

随机推荐

  1. Using SQLXML Bulk Load in the .NET Environment

    http://msdn.microsoft.com/en-us/library/ms171878.aspx 1.首先创建一张表 CREATE TABLE Ord ( OrderID ,) PRIMAR ...

  2. 【同步时间】Linux设置时间同步

    所有节点都要确保已安装ntpd(在步骤4已安装) 1.首先选择一台服务器作为时间服务器. 假设选定为node1.sunny.cn服务器为时间服务器. 2.ntp服务器的配置 修改ntp.conf文件: ...

  3. 使用 shinydashboard

    除了 shiny 扩展包提供的函数之外,RStudio 也开发了一个 shinydashboard 扩展包 (http://rstudio.github.io/shinydashboard/),它呈现 ...

  4. git-it 教程,一些git知识点。/ 如何解决merge conflict/ 如何使用Github Pages./Git术语表

    一个git使用教程 https://:.com/jlord/git-it-electron#what-to-install 一个在线Github的功能教学:https://lab.github.com ...

  5. 2016 CCPC Hangzhou Onsite

    A:题意:n个格子排成一排,每个a[i],要求重排成k个,每个人数相同,合并两个和划分成两个(可以不等)都是花费为1,问最小花费 题解:从前往后贪心即可,由于哪个地方忘开ll,wa了,全改成ll就过了 ...

  6. HTML5-canvas实例:2D折线数据图与2D扇形图

    基础知识: <canvas id="demo" width="400" height="400"></canvas> ...

  7. 使用Spring Loader或者Jrebel实现java 热部署

    .其实JRebel和Spring-Loaded就是一个开发环境下的利器,skip build and redeploy process,大大提升了工作效率!而非生产环境的利器...因为线上reload ...

  8. MySql中Blob与Text的区别

    BLOB是一个二进制大对象,可以容纳可变数量的数据.有4种BLOB类型:TINYBLOB.BLOB.MEDIUMBLOB和LONGBLOB.它们只是可容纳值的最大长度不同. 有4种TEXT类型:TIN ...

  9. Java9新特性

    转载:http://blog.csdn.net/qq_32524177/article/details/77014757 写在前面的话:Java9来了,搜索了很多关于Java9的新特性,但文献不多,特 ...

  10. C# 对json对象嵌套数组

    看图: 这里可以看到是二层嵌套!!使用C#如何实现?? 思路:使用list集合实现 → 建立类 → list集合 → 微软的   Newtonsoft.Json  (一款.NET中开源的Json序列化 ...