0
点赞
收藏
分享

微信扫一扫

Android客户端HTTP请求服务端Servlet,android开发技术基础

三分梦_0bc3 2022-03-19 阅读 77

这里我使用HttpURLConnection测试请求的过程,要使用必需添加依赖:

useLibrary 'org.apache.http.legacy'

android 6.0(api23) 后,不再提供org.apache.http.(只保留几个类).*

[]( )

article/details/90906126)3. 客户端测试代码

客户端根据以上servlet返回的json字符做相应请求。代码如下:

public static void testHttpURLConnection() {

final String path ="http://192.168.100.47:8080/Android/servlet/LoginServlet";// 1.获取请求的路径

HttpURLConnection conn = null;

InputStream is = null;

try {

// 2.获取url对象

URL url = new URL(path);

// 3.得到连接的对象

conn = (HttpURLConnection) url.openConnection();

// 4.设置连接的参数

// 设置请求方式

//conn.setRequestMethod("GET");

conn.setRequestMethod("POST");

// 设置连接超时时间

conn.setConnectTimeout(5000);

// 设置读取数据的超时时间

conn.setReadTimeout(5000);

conn.setUseCaches(false);// Post 请求不能使用缓存

// 设置允许读取服务器端返回的数据

conn.setDoInput(true);

// 5.连接服务器

//conn.connect();//如果是post请求,不要加这个,否则可能IllegalStateException: Already connected

//如果是get请求,参数写url中,就不需要post参数

conn.setDoOutput(true);//4.0中设置httpCon.setDoOutput(true),将导致请求以post方式提交

final OutputStream outputStream = conn.getOutputStream();

outputStream.flush();

outputStream.write("username=zhangsan".getBytes("UTF-8"));

outputStream.close();

// 6.获取返回的服务器端的响应码。

int responseCode = conn.getResponseCode();

// 7.只有响应码是200时,方可正常读取

if (200==responseCode) {

is = conn.getInputStream();

// 将获取的输入流中的数据转换为字符串

final String content=StreamTools.readStream(is);

LogUtils.debug(TAG,"content="+content);

}else{

LogUtils.debug(TAG,"responseCode="+responseCode);

}

}catch (Exception e){

LogUtils.debug(TAG,e.toString());

}

}

将接受到的字节流转化成字符串,UTF-8编码格式。

public static String readStream(InputStream in) throws Exception{

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int len = -1;

byte buffer[] = new byte[1024];

while((len=in.read(buffer))!=-1){

baos.write(buffer, 0, len);

}

in.close();

return new String(baos.toByteArray(),"UTF-8");

//return new String(baos.toByteArray());

}

以上代码,get和post请求写在了一起。如果是get请求,就把参数写在url地址上面,否则以流的形式向服务端发送。

servlet返回的形式,通常的接口都以json格式返回result,方便解析处理。如:

{"name":"zhangsan"}

结尾

我还总结出了互联网公司Android程序员面试涉及到的绝大部分面试题及答案,并整理做成了文档,以及系统的进阶学习视频资料分享给大家。
(包括Java在Android开发中应用、APP框架知识体系、高级UI、全方位性能调优,NDK开发,音视频技术,人工智能技术,跨平台技术等技术资料),希望能帮助到你面试前的复习,且找到一个好的工作,也节省大家在网上搜索资料的时间来学习。

image

举报

相关推荐

0 条评论