一、总结get命令:(对于HttpURLConnection和HTTPClient都是一样的)
1、设置到url就行,因为get命令的请求参数就是在请求行里面,是包装在url里面的,所以只要用url连接好 了服务器,就可以获取读取流来都内容。
用getResponseCode来判断一下是否连接成功,成功以后就调用getInputStream()来读取内容。
例如:(HttpURLConnection)
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- // 设置连接超时时间
- urlConn.setConnectTimeout(5 * 1000);
- // 开始连接
- urlConn.connect();
- // 判断请求是否成功
- if (urlConn.getResponseCode() == HTTP_200) {
- // 获取返回的数据
- byte[] data = readStream(urlConn.getInputStream());
-
例如:(HTTPClient)
- String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
- // 新建HttpGet对象
- HttpGet httpGet = new HttpGet(path);
- // 获取HttpClient对象
- HttpClient httpClient = new DefaultHttpClient();
- // 获取HttpResponse实例
- HttpResponse httpResp = httpClient.execute(httpGet);
- // 判断是够请求成功
- if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
- // 获取返回的数据
- String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
二、总结post命令:
1、先用url指定访问的资源。
2、因为在httpURLConnection里面默认的参数都是get命令的,所以在使用post命令的时候要这样设置:(这是对于httpURLConnection)
- // Post请求必须设置允许输出
- urlConn.setDoOutput(true);
- // Post请求不能使用缓存
- urlConn.setUseCaches(false);
- // 设置为Post请求
- urlConn.setRequestMethod("POST");
- urlConn.setInstanceFollowRedirects(true);
- // 配置请求Content-Type
- urlConn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencode");
3、因为post命令是把请求的参数写在正文里面的,所以就要先把参数写到正文里面去。如下:
例如(HttpURLConnection):
- DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
- dos.write(postData);
- dos.flush();
- dos.close();
- // 判断请求是否成功
- if (urlConn.getResponseCode() == HTTP_200) {
- // 获取返回的数据
- byte[] data = readStream(urlConn.getInputStream());
- HttpPost httpPost = new HttpPost(path);
- // Post参数
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("id", "helloworld"));
- params.add(new BasicNameValuePair("pwd", "android"));
- // 设置字符集
- HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
- // 设置参数实体
- httpPost.setEntity(entity);
- // 获取HttpClient对象
- HttpClient httpClient = new DefaultHttpClient();
- // 获取HttpResponse实例
- HttpResponse httpResp = httpClient.execute(httpPost);
- // 判断是够请求成功
- if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
- // 获取返回的数据
- String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
- Log.i(TAG_HTTPGET, "HttpPost方式请求成功,返回数据如下:");
- Log.i(TAG_HTTPGET, result);
- } else {
- Log.i(TAG_HTTPGET, "HttpPost方式请求失败");
- }