Android网络上传数据

1.servlet
public class NewsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String title=request.getParameter("title");
        title=new String(title.getBytes(),"UTF-8");
        String timeLength=request.getParameter("timeLength");
        System.out.println(title+":"+timeLength);
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

2.MainActivity
public void save(View view){
        EditText titleText=(EditText)findViewById(R.id.title);
        EditText lengthText=(EditText)findViewById(R.id.timeLength);
        String title=titleText.getText().toString();
        String length=lengthText.getText().toString();
        VideoNewsService service=new VideoNewsService();
        try {
            service.save(title,length);
            Toast.makeText(getApplicationContext(), "保持成功",2);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "保持失败",2);
        }
    }

3.上传参数VideoNewsService.java 
public void save(String title, String length) throws Exception{
        String path="http://192.168.0.112:8080/Test1/news.do";
        Map<String,String> datas=new HashMap<String,String>();
        datas.put("title",title);
        datas.put("timeLength",length);
        //sendGetRequest(path,datas,"UTF-8");
        sendPostRequest(path,datas,"UTF-8");
    }

    /**
     * POST提交参数
     */
    private void sendPostRequest(String path, Map<String, String> datas,String encoding) throws Exception {
        StringBuffer data=new StringBuffer();
        if(datas!=null&&datas.size()>0){
            for(Map.Entry<String,String> entry:datas.entrySet()){
                
                data.append(entry.getKey()+"=");
                data.append(URLEncoder.encode(entry.getValue(),encoding)+"&");
            }
            //得到实体数据
            byte[] entity=data.toString().getBytes();
            HttpURLConnection con=(HttpURLConnection) new URL(path).openConnection();
            con.setConnectTimeout(5000);
            con.setRequestMethod("POST");
            //设置HTTP请求头,不使用cookie的情况下,其余头内容均可省略,除了下面的内容
            con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            con.setRequestProperty("Content-Length",String.valueOf(entity.length));
            
            con.setDoOutput(true);//允许对外写数据
            OutputStream os=con.getOutputStream();
            os.write(entity);
            if(con.getResponseCode()==200){
                Log.i("Post","请求成功");
            }
        }
    }

    /**
     * GET提交参数
     */
    private void sendGetRequest(String path, Map<String, String> datas,String encoding) throws Exception{
        StringBuffer url=new StringBuffer(path);
        url.append("?");
        for(Map.Entry<String,String> entry:datas.entrySet()){
            
            url.append(entry.getKey()+"=");
            url.append(URLEncoder.encode(entry.getValue(),encoding)+"&");
        }
        URL server=new URL(url.toString());
        HttpURLConnection con=(HttpURLConnection) server.openConnection();
        con.setReadTimeout(5000);
        con.setRequestMethod("GET");
        if(con.getResponseCode()!=200){
            throw new Exception();
        }
    }

5.Android内部集成HttpClient进行Http相关操作
//HttpClient发送POST请求,封装较多,性能不高
    private void httpClientRequest(String path, Map<String, String> datas,
            String encoding) throws Exception {
        // 1.HttpClient默认集成,不需要手动加入jar
        // 2.HttpClient采用NameValuePair存放键值对参数
        List<NameValuePair> pairs=new ArrayList<NameValuePair>();
        if(datas!=null&&datas.size()>0){
            for(Map.Entry<String,String> entry:datas.entrySet()){
                pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        
        //组装post请求
        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,encoding);
        HttpPost httpPost=new HttpPost(path);
        httpPost.setEntity(entity);
        
        //发送请求
        DefaultHttpClient client=new DefaultHttpClient();
        HttpResponse response=client.execute(httpPost);
        if(response.getStatusLine().getStatusCode()==200){
            Log.i("httpClient","HttpClient请求成功");
        }
    }


你可能感兴趣的:(Android网络上传数据)