android客户端访问网络工具类
16lz
2021-12-04
package com.yqq.loginclient.utils;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Reader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * 连接服务器 * * @author yqq_coder * */public class LoginUtils {public LoginUtils() {// TODO Auto-generated constructor stub}/** * http://10.1.17.208:8080/LoginService/LoginServlet?userName=Lihua&passWord=123456 * http://localhost:8080/?userName=Lihua&passWord=123456 * @param ip 服务器IP * @param userName GET方式传递参数用户名 * @param passWord 密码 * @return */public static String connect(String ip, String userName, String passWord) {String str = "http://" + ip+ ":8080/LoginService/LoginServlet?userName="+userName+"&passWord="+passWord;URL url=null;InputStream inputStream = null;HttpURLConnection connection = null;StringBuffer sb = null;// 线程安全try {url = new URL(str);//获得URL对象try {connection = (HttpURLConnection) url.openConnection();connection.setConnectTimeout(3000);connection.setRequestMethod("GET");//GET方式提交参数connection.setDoOutput(true);//设置可以向服务器读写connection.setDoInput(true);//请求成功if (connection.getResponseCode() == 200) {inputStream = connection.getInputStream();Reader reader = new InputStreamReader(inputStream, "UTF-8");//打包成字符流BufferedReader bufferedReader = new BufferedReader(reader);String str1 = null;sb = new StringBuffer();while ((str1 = bufferedReader.readLine()) != null) {sb.append(str1);}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (MalformedURLException e) {e.printStackTrace();//关闭流很重要} finally {if (inputStream != null) {try {inputStream.close();inputStream = null;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (connection != null) {connection.disconnect();connection = null;}}if (sb != null) {return new String(sb);}return "服务器异常!";}}
更多相关文章
- mybatisplus的坑 insert标签insert into select无参数问题的解决
- Python技巧匿名函数、回调函数和高阶函数
- python list.sort()根据多个关键字排序的方法实现
- android Gallery 详解
- 模拟android访问服务器
- Android(安卓)Okhttp的基础使用版
- android登录超时显示demo
- Android全屏设置的两种方式
- Android中Fragment的Arguments