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

2018-03-11  本文已影响0人  紫杉叶子
笔记如下
<uses-permission android:name="android.permission.INTERNET"/>

1.HttpURLConnection

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

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'
}
HttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet();

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

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


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();

上一篇下一篇

猜你喜欢

热点阅读