网络操作基础
来源:互联网 发布:巩义网络招聘平台 编辑:程序博客网 时间:2024/05/21 14:06
1.HttpURLConnection:
GET:
private void sendRequestWithHttpURLconnection () { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL("http://bing.com"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } showResponse(response.toString()); } catch (Exception e){ e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } } }).start();}private void showResponse(final String response) { runOnUiThread(new Runnable() { @Override public void run() { responseTest.setText(response); } });}
POST:
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=233");
2.OKHttp
GET:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://g.cn").build();
Response respone = client.newCall(request).execute();
String responseData = response.body().string
POST:
Request requestBody = new FormBody.Builder().add("username","admin").add("password","666").build();
Request request = newe Request.Builder().url("http://g.cn").post(requestBody).build();
compile 'com.squareup.okhttp3:okhttp:3.6.0'
private void sendRequestWithOKHttp() { new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://bing.com").build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); showResponse(responseData); } catch (Exception e) { e.printStackTrace(); } } }).start();}
3.XML解析:
3.1 PULL:
private void parseXMLWithPull(String xmlData) { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xmlPullParser = factory.newPullParser(); xmlPullParser.setInput(new StringReader(xmlData)); int eventType = xmlPullParser.getEventType(); String id = ""; String name = ""; while (eventType != XmlPullParser.END_DOCUMENT) { String nodeName = xmlPullParser.getName(); switch (eventType) { case XmlPullParser.START_TAG: if ("id".equals(nodeName)){ id = xmlPullParser.nextText(); } else if ("name".equals(nodeName)){ name = xmlPullParser.nextText(); } break; case XmlPullParser.END_TAG: if ("app".equals(nodeName)){ Log.d("MainActivity","id is " + id); Log.d("MainActivity","name is " + name); } break; default: break; } eventType = xmlPullParser.next(); } } catch (Exception e) { e.printStackTrace(); }}
3.2 SAX:
public class ContentHandler extends DefaultHandler { private String nodeName; private StringBuilder id; private StringBuilder name; @Override public void startDocument() throws SAXException { id = new StringBuilder(); name = new StringBuilder(); } @Override public void startElement(String uri, String localName, Attributes attributes) throws SAXException { nodeName = localName; } @Override public void characters(char[] ch,int start,int length) throws SAXException { if ("id".equals(nodeName)) { id.append(ch,start,length); } else if ("name".equals(nodeName)) { name.append(ch,start,length); } } @Override public void endElement(String uri,String localName,String qName) throws SAXException { if ("app".equals(localName)) { Log.d("ContentHandler","id is " + id); Log.d("ContentHandler","name is " + name); id.setLength(0); name.setLength(0); } } @Override public void endDocument() throws SAXException{ super.endDocument(); }}
private void parseXMLWithSAX(String xmlData) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); ContentHandler handler = new ContentHandler(); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(new StringReader(xmlData))); } catch (Exception e) { e.printStackTrace(); }}
4.JSON解析:
4.1 JSONObject:
private void parseJSONWithJSONObject(String jsonData) { try { JSONArray jsonArray = new JSONArray(jsonData); for (int i=0;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String id = jsonObject.getString("id"); String name = jsonObject.getString("name"); Log.d("MainActivity","id is " + id); Log.d("MainActivity","name is " + name); } }catch (Exception e) { e.printStackTrace(); }}
4.2 GSON:
compile 'com.google.code.gson:gson:2.8'
private void parseJSONWithGSON(String jsonData) { Gson gson = new Gson(); List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getRawType()); for (App app:appList) { Log.d("MainActivity","id is " + app.getId()); Log.d("MainAcitvity","name is " + app.getName()); }}
5.封装网络操作:
public class HttpUtil { public static void sendOkHttpRequest(String address,okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); }}
调用:
String address = "http://zcsj8.pe.hu";HttpUtil.sendOkHttpRequest(address,new okhttp3.Callback() { @Override public void onResponse(Call call, Response response) throws IOException { String responsData = response.body().string(); showResponse(responsData); } @Override public void onFailure(Call call,IOException e) { }});
阅读全文
0 0
- 网络操作基础
- iOS网络操作基础
- linux基础操作--网络配置
- Retrofit网络请求框架基础操作
- Linux 网络和监控基础命令操作
- Android基础之HTTP操作及SOCKET网络操作
- android 基础 文件下载 文件操作 网络操作
- Android基础 —— 网络连接操作NetWork
- linux基础(六)----linux命令系统学习----网络操作命令
- 网络编程:自定义强大的C#网络操作基础类(NetHelper)
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 人脸捕捉与WEB端的活体检测
- HDU 3663 Power Stations(Dancing_Links精确覆盖)
- 241. Different Ways to Add Parentheses
- iOS 使用Application Loader提交你的应用
- 素数筛选法简单介绍
- 网络操作基础
- 秋招数据库
- 模板方法设计模式
- python写的整本书的小说爬虫(并写入txt文件)
- <c:foreach>同时遍历两个List的方法
- 关于类
- fileupload的问题
- 代码覆盖度工具OpenCppCoverage(cpp)、EclEmma(java)、Coverage(python)使用
- java笔记(一)