2018-03-09 android下提交数据(request)(一)

笔记如下
  • 首先开启权限
<uses-permission android:name="android.permission.INTERNET"/>

1.HttpURLConnection

  • get
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);

  • post
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");

//设置以表单的类型提交
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//String data = "number=" + number + "&pwd=" + pwd;
String data = "number="+ URLEncoder.encode(number, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");
conn.setRequestProperty("Content-Length", data.length()+"");


//表示向服务器写数据
conn.setDoOutput(true);
conn.getOutputStream().write(data.getBytes());
conn.setConnectTimeout(5000);

 int code = conn.getResponseCode();

2.HttpClient
注:这套api已经被谷歌废弃,想要使用就要在module的build.gradle中加上

android {
    useLibrary 'org.apache.http.legacy'
}
  • get
HttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet();

//get:相当于浏览器点回车
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();

//得到响应的实体内容
InputStream in = response.getEntity().getContent();


  • post
HttpClient client = new DefaultHttpClient();
HttpPost post  = new HttpPost(path);
List<NameValuePair> list = new ArrayList<NameValuePair>();

list.add(new BasicNameValuePair("number",number));
list.add(new BasicNameValuePair("pwd",pwd));
//设置要带给服务器的实体
post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));

HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();

//得到响应的实体内容
InputStream in = response.getEntity().getContent();

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,314评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,933评论 18 139
  • 有些事过去了就是过去了,就是回忆。 当时我们读初中,和A一起的一个人老师都说长的很俊,但我却觉得他长的最帅。他学习...
    君之颜阅读 196评论 0 0
  • (一) 北京这几天特别冷,道馆里的窗上结满了冰霜。这个现象来北京十几年好像第一次遇到。想起了东北老家,阳台里面的墙...
    大师兄仁仁爱阅读 255评论 0 0
  • 抱怨没有任何作用,一定要想办法去解决眼前的问题和矛盾。 你为什么要努力,现在知道了吧,就是要证明给自己看,我不比任...
    七月的安安阅读 113评论 0 0