访问网络API
原生:
-
java.net.HttpURLConnection;
-
get
URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置连接参数 conn.setRequestMethod("GET"); conn.setConnectTimeout(8000); conn.setReadTimeout(8000); if(conn.getResponseCode() == 200){ // 获取输入流 InputStream is = conn.getInputStream(); // 从输入流中读取服务器返回的数据 String text = Tools.getTextFromStream(is); }
-
post
URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 连接参数 conn.setRequestMethod("POST"); conn.setConnectTimeout(8000); conn.setReadTimeout(8000); // 要发送的请求数据 String content = "name=" + URLEncoder.encode(name) + "&pass=" + pass; // 设置请求头 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", content.length() + ""); // 开启客户端输出流 conn.setDoOutput(true); // 获取客户端输出流 OutputStream os = conn.getOutputStream(); // 把请求数据发送给服务器 os.write(content.getBytes()); if(conn.getResponseCode() == 200){ // 获取输入流 InputStream is = conn.getInputStream(); // 从输入流中读取服务器返回的数据 String text = Tools.getTextFromStream(is); }
-
-
org.apache.http.client.HttpClient;
-
android 6.0(api 23) SDK,不再提供org.apache.http.*(只保留几个类).
-
get
HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(urlString); HttpResponse response = client.execute(get); StatusLine sl = response.getStatusLine(); if(sl.getStatusCode() == 200){ HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); String text = Tools.getTextFromStream(is) }
-
post
AsyncHttpClient client = new AsyncHttpClient(); RequestParams rp = new RequestParams(); rp.add("name", name); rp.add("pass", pass); client.get(path, rp, new MyResponseHandler()); class MyResponseHandler extends AsyncHttpResponseHandler{ @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { // statusCode:状态码 // Header[] headers:响应头 // byte[] responseBody:响应正文,是一个字符数组 String text = new String(responseBody); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { String text = new String(responseBody); } }
-
三方:
- OKhttp(口碑好):http://blog.csdn.net/lmj623565791/article/details/47911083
- xUtils(功能多):https://github.com/wyouflf/xUtils
网友评论