我是靠谱客的博主 体贴芝麻,最近开发中收集的这篇文章主要介绍HTTP通信--Android客户端与Servlet通信android客户端Servlet端,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
android客户端
//设置一个handler对象(新开一个Thread需要一个handler对象发送message)
//根据发送过来的message进行相关的操作
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Log.i("handler",msg.obj.toString());
break;
}
}
};
//新建一个方法负责开启新线程和HTTP通信
public void httpcon(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
//设置post请求
connection.setRequestMethod("POST");
//如要进行POST请求下面两个必须设置
connection.setDoInput(true);//开启输出
connection.setDoOutput(true);//开启输入
connection.connect();
//传送JSON数据
Gson gson = new Gson();
OutputStream os = connection.getOutputStream();//创建输出流
os.write(gson.toJson(lp).getBytes());//通过流传输数据
os.flush();
os.close();
if (HttpURLConnection.HTTP_OK == connection.getResponseCode())
Log.i("flag","连接成功");
//读取服务端的响应信息
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String read = "";
StringBuilder result = new StringBuilder();
while ((read = reader.readLine()) != null)
result.append(read);
Log.i("flag2",result.toString());
//创建MESSAGE
Message message = handler.obtainMessage();
message.what = 1;
message.obj = result;
handler.sendMessage(message);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
connection.disconnect();
}
}
}).start();
Servlet端
尚未解决的问题①1.
public class DataUploading extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置request,response的编码,避免出现中文乱码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
Connection con;
//创建输入流,获取从客户端发送过来的信息
InputStream is = request.getInputStream();
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"));//utf-8解决中文乱码
String read = "";
StringBuilder result = new StringBuilder();
while((read = reader.readLine()) != null) {
result.append(read);
}
System.out.print(result.toString());
response.getOutputStream().write(result.toString().getBytes("UTF-8"));;
//使用getOutputStream.write输出响应信息给客户端
//getOutputStream.write输出为字节,所以要用getBytes("UTF-8")避免中文乱码。
//亦可使用PrintWriter进行字符输出
//PrintWriter out = response.getWriter();
//out.print();
}
}
- 如果在doGet方法中使用this.dopost(),response的信息将不会打印在网页的页面上。 ↩
最后
以上就是体贴芝麻为你收集整理的HTTP通信--Android客户端与Servlet通信android客户端Servlet端的全部内容,希望文章能够帮你解决HTTP通信--Android客户端与Servlet通信android客户端Servlet端所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复