Android在线程中创建一个POST请求

    近日开发项目中遇到需要Android端与服务器进行网络通信的,网上资料找了一些大多数不好用或者代码不完整,找到一个能用的,稍加更改,就成了我的了,哈哈哈!

Android 端:

package com.example.votesys;

import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import static com.example.votesys.VotingActivity.post_url;

/**
 * Created by xiaowen on 2017/12/30.
 */
//使用POST更好
public class NetWorkService {


    /**
     * 使用post方式与服务器通讯
     * @param content
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String SendPostRequest(String content){
        HttpURLConnection conn = null;
        try {
            String Strurl = post_url;
            URL url = new URL(Strurl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("ser-Agent", "Fiddler");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setConnectTimeout(5 * 1000);
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(URLEncoder.encode(content.toString(), "UTF-8").getBytes());
            outputStream.flush();
            outputStream.close();
            if(HttpURLConnection.HTTP_OK==conn.getResponseCode()){
                Log.i("PostGetUtil","post请求成功");

                InputStream inputStream = conn.getInputStream();
                String backcontent = new BufferedReader(new InputStreamReader(inputStream))
                        .lines().parallel().collect(Collectors.joining(System.lineSeparator()));
                backcontent= URLDecoder.decode(backcontent,"UTF-8");
                System.out.println(" 这是从服务器返回来的信息: "+backcontent);
                Log.i("PostGetUtil",backcontent);
                inputStream.close();
                return backcontent;
            }else {
                Log.i("PostGetUtil","post请求失败");return "not ok";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            conn.disconnect();
        }
        return "error";
    }

    /**
     * 使用get方式与服务器通信
     * @param content
     * @return
     */
//    public static String SendGetRequest(String content){
//
//        HttpURLConnection conn=null;
//        try {
//
//            String Strurl="http://192.168.0.6:8080/test2/MyServlet?"+content;
//            URL url = new URL(Strurl);
//            conn = (HttpURLConnection) url.openConnection();
//            conn.setConnectTimeout(5000);
//            conn.setRequestMethod("GET");
//            if(HttpURLConnection.HTTP_OK==conn.getResponseCode()){
//                Log.i("PostGetUtil","get请求成功");
//                InputStream in=conn.getInputStream();
//                byte[] bytes = new byte[0];
//                bytes = new byte[in.available()];
//                in.read(bytes);
//                String backcontent = new String(bytes);
//
//                backcontent= URLDecoder.decode(backcontent,"UTF-8");
//                Log.i("PostGetUtil",backcontent);
//                in.close();
//                return "httpisok";
//            }
//            else {
//                Log.i("PostGetUtil","get请求失败");return "fail";
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        finally{
//            conn.disconnect();
//        }
//        return "exception";
//    }
}

Servlet端:

package voteSystem;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class MyServlet
 */
@WebServlet("/Servlet1")//web.xml中不用配置servlet-mapping
public class Servlet1 extends HttpServlet {
    private static final long serialVersionUID = 1L;
    static Thread thread = null;
    static CountDownLatch count = new CountDownLatch(1);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet1() {
        super();
        // TODO Auto-generated constructor stub
       
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求发送的数据
//        String content=request.getQueryString();
       content=URLDecoder.decode(content,"UTF-8");
//        System.out.println("1="+content);
//
//        //向客户端返回数据
//        OutputStream os=response.getOutputStream();
//        String back="你好,我是服务端,收到get请求,正在处理!!!";
//        os.write(URLEncoder.encode(back,"UTF-8").getBytes());
//        os.flush();
//        os.close();
//    	doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取post请求发送的数据
    	System.out.println("开始Servlet1");
    	InputStream inputStream = request.getInputStream();
    	
    	String content = new BufferedReader(new InputStreamReader(inputStream))
    	.lines().parallel().collect(Collectors.joining(System.lineSeparator()));
        System.out.println("收到post请求");
        content=URLDecoder.decode(content,"UTF-8");//这里是处理后的内容
        System.out.println("收到post请求,json是:"+content);
        
        //servlet传递数据到jsp
        System.out.println("前");              
        System.out.println("后");
        List< Map> list = toListMap(content); //此行json转换为list
        System.out.println("list"+list.toString());       
        ServletContext application=this.getServletContext();   
        application.setAttribute("list", content);
       
//        向客户端返回数据,阻塞等待数据

  
   //      try {
   //         count.await();
   //    } catch (InterruptedException e) {
   //         e.printStackTrace();
   //    } 
   //    System.out.println("All is finished.");
   //     count = new CountDownLatch(1);
        
        		OutputStream os=response.getOutputStream();
             String back="你好,我是服务端,收到post请求,正在处理!!!";
              os.write(URLEncoder.encode(back,"UTF-8").getBytes());
              os.flush();
              os.close();
              break;
//        	}
//        }
       
        System.out.println("结束Servlet1,投票结果如下:");
    }
    public static List> toListMap(String json){
        List list =JSON.parseArray(json);
         
        List< Map> listw = new ArrayList>();
        for (Object object : list){
            Map ageMap = new HashMap();
            Map  ret = (Map) object;//取出list里面的值转为map
            listw.add(ret);
        }
        return listw;
         
    }
} 
  

调用:

public void makePost(){
        netWorkService = new NetWorkService();
        String str1 = netWorkService.SendPostRequest(VotingActivity.PostString);
        //上面这两句就够了,下面的是别的处理
        Toast.makeText(VotingActivity.this,str1,Toast.LENGTH_SHORT).show();

        String str2 = str1.substring(1,str1.length()-1);
        String res[]= str2.split(", ");
        for(int i=0;i

因为我的POST是个耗时操作,需要等服务器那边处理完用户提交的数据才能返回给我Android端的数据,所以调用POST请求不能放在Activity中(就是主线程),不然会出现假死状态,那么就要放到子线程中去请求POST。

总结起来就是  主线程不做耗时操作,子线程不更新UI(这个以后会更新相关说明)。

子线程使用:

//创建一个子线程的类
 class MyThread extends Thread{

        public MyThread(String threadName) {
            super(threadName);
            System.out.println("开始调用start()方法");
            start();
        }

        @Override
        public void run() {
            System.out.println("开始执行子线程");
            Looper.prepare();//增加部分
            makePost();
            Looper.loop();//增加部分
        }

    }

//在onCreate方法里或者其他需要的地方(比如按钮监听)
new MyThread("child Thread");//耗时操作放在线程里

PS:贴完这些代码我发现一个矛盾:鄙人觉得网上这些无良网友贴一些不全的代码让人使用起来困难重重,甚至有些恼火,但当我要分享某个功能点或者说技术点时,这些代码并不是单独地放在那,拿出来就能分享(也可能鄙人代码写的不够低耦合),需要我去加一些注释解释代码,而且分享时我也没有单独新建一个工程去验证自己贴的代码是否可以运行,这大概就是网上那些不全的代码的原因吧(大家本来想做好事,但无形中做了一个坏人)。

果然人总是会活成自己讨厌的样子。

你可能感兴趣的:(Android)