HttpClient和HttpURLConnection
2016-05-18 12:08
483 查看
HttpClient
xutil 连接 最简单的
package com.example.day06_httpclient; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.DefaultClientConnection; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { String key = "3ac9f31ff66b9746539472887b3799c3"; String path = "http://web.juhe.cn:8080/constellation/getAll"; String get_path = "http://web.juhe.cn:8080/constellation/getAll?consName=狮子座&type=today&key=" + key; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(){ @Override public void run() { // TODO Auto-generated method stub // get(); post(); } }.start(); } protected void post() { // TODO Auto-generated method stub HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(path); try { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("consName", "狮子座")); parameters.add(new BasicNameValuePair("type", "year")); parameters.add(new BasicNameValuePair("key", key)); // 实体数据中需要放入集合数据 HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf-8"); // post 中应该包含实体数据 httpPost.setEntity(entity ); // 用带有地址的httppost请求 HttpResponse httpResponse = httpClient.execute(httpPost); if(httpResponse.getStatusLine().getStatusCode()==200){ System.out.println("连接成功"); HttpEntity httpEntity = httpResponse.getEntity(); System.out.println(EntityUtils.toString(httpEntity)); }else{ System.out.println("连接失败"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ } } private void get() { // 建立请求 HttpClient httpClient = new DefaultHttpClient(); // 建立请求类型 HttpGet httpGet = new HttpGet(get_path); try { // 执行请求的地址 获得响应的东西 HttpResponse httpResponse = httpClient.execute(httpGet); // 获取响应的实体 HttpEntity entity = httpResponse.getEntity(); String string = EntityUtils.toString(entity); System.out.println(string); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }HttpURLConnection
package com.example.day06_httpclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.BreakIterator; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class HttpURLConnectionActivity extends Activity { String get_path = "http://web.juhe.cn:8080/constellation/getAll?consName=%E7%8B%AE%E5%AD%90%E5%BA%A7&type=today&key=3ac9f31ff66b9746539472887b3799c3"; private BufferedReader br; private HttpURLConnection httpURLConnection; String path = "http://web.juhe.cn:8080/constellation/getAll"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_http_urlconnection); new Thread() { @Override public void run() { // getData(); getDataPost(); } }.start(); } protected void getDataPost() { // TODO Auto-generated method stub try { URL url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); //设置连接 httpURLConnection.setConnectTimeout(5000); httpURLConnection.setReadTimeout(5000); httpURLConnection.setRequestMethod("POST"); OutputStream outputStream = httpURLConnection.getOutputStream(); // 建立连接 httpURLConnection.connect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void getData() { URL url; try { url = new URL(get_path); httpURLConnection = (HttpURLConnection) url.openConnection(); // 设置连接的限制 httpURLConnection.setConnectTimeout(5000); httpURLConnection.setReadTimeout(5000); httpURLConnection.setRequestMethod("GET"); // 开始链接 httpURLConnection.connect(); // int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { System.out.println("连接成功"); InputStream inputStream = httpURLConnection.getInputStream(); br = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); String str = null; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str.trim()); } br.close(); System.out.println(sb.toString()); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } }
xutil 连接 最简单的
// 通过网址获得信息 private void getData(final int i, String path) { HttpUtils httpUtils = new HttpUtils(); // 配置当前网络缓存到期时间 (0秒内数据那缓存数据)默认60s httpUtils.configCurrentHttpCacheExpiry(0); // 开始连接,RequestCallBack<T>是得到的数据类型 httpUtils.send(HttpMethod.GET, path, new RequestCallBack<String>() { private NewsDetails newsDetails; @Override public void onFailure(HttpException arg0, String arg1) { // 失败的方法 Toast.makeText(context, "网络连接错误,请稍后再试", 0).show(); } @Override public void onSuccess(ResponseInfo<String> arg0) { // 成功执行方法 String result = arg0.result; // 转化为流的方法 ByteArrayInputStream inputStream = new ByteArrayInputStream( result.getBytes()); // 这里是在子线程中,所以需要handler handler.sendEmptyMessage(i); } }); }
相关文章推荐
- Andorid Launcher程序代码分析
- Messenger实现Android IPC
- 用ActionBar+Fragment实现Tab分类列表
- android gralloc 流程分析
- Android帧缓冲区(Frame Buffer)硬件抽象层(HAL)模块Gralloc的实现原理分析
- ListView子控件抢占焦点的问题
- 一个监听器绑定多个按钮控件
- Android API Level
- AlertDialog类的使用
- 在onTabSelected里面调用viewPager.setCurrentItem方法发生java.lang.NullPointerException错误
- Unity java C 互调
- Github官方app分析——用户身份验证模块
- android下文件访问权限及修改
- Andorid Unable to execute dex: Multiple dex files define Lorg/apache/commons/collections/Buffer
- Application did not close the cursor or database object that was opened here 异常
- Asynctask异步处理类的使用
- The connection to adb is down, and a severe error has occured.
- Andorid开发第一个程序HelloWorld
- handler机制的原理
- React Native官方实例UIExplorer项目(for android)运行遇到的问题