android调用springmvc写的restful

下载srpingmvc的相关jar

http://www.cnblogs.com/liuhongfeng/p/4919963.html

配置spingmvc和相关接口

http://blog.csdn.net/jianyuerensheng/article/details/51258942


如果报错,检查JDK版本是否和本地的一致

在UserController.jave中添加接口

package com.zjn.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zjn.entity.User;

/**
 * 用户管理
 * 
 * @author zjn
 */
@Controller
public class UserController {

	@RequestMapping("")
	public String Create(Model model) {
		return "create";
	}

	@RequestMapping("/save")
	public String Save(@ModelAttribute("form") User user, Model model) { // user:视图层传给控制层的表单对象;model:控制层返回给视图层的对象
		model.addAttribute("user", user);
		return "detail";
	}
	
	@RequestMapping(value="/Restfull",method=RequestMethod.POST)  
	public String Restfull(@ModelAttribute("form") User user, HttpServletRequest request,HttpServletResponse response) throws Exception {
        request.setAttribute("name",user.getAge()+ user.getName() + user.getPwd());
        return "list";
    }
	
	@RequestMapping(value="/RestfullGet/{proId}",method=RequestMethod.GET)  
	public String RestfullGet(@PathVariable String proId, HttpServletRequest request,HttpServletResponse response) throws Exception {
        request.setAttribute("name", proId);
        return "list";
    }
	
	@RequestMapping(value="/RestfullMGet/{name}/{pwd}",method=RequestMethod.GET)
    public String RestfullMGet(@ModelAttribute("form") User user, HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.setAttribute("name", user.getName() + "------" + user.getPwd());
		return "list";
    }
	
	@RequestMapping(value="/RestfullM1Get/{name}/{pwd}",method=RequestMethod.GET)
    public ModelAndView RestfullM1Get(@PathVariable String name,
    		@PathVariable String pwd) {
		System.out.println(name + "------" + pwd);
		Map map1 = new HashMap();
		  map1.put("name", name + "------" + pwd);
		return new ModelAndView( "/list", map1);  
    }
	
	@RequestMapping(value="/RestfullAGet/{proId}",method=RequestMethod.GET)  
	public @ResponseBody String RestfullAGet(@PathVariable String proId, HttpServletRequest request,HttpServletResponse response) throws Exception {
        request.setAttribute("name", proId);
        return "backinfo:" + proId;
    }
}

在create.jsp中条码web调用接口的方法

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




Add User From


	
创建用户


GET00001
GET0000100002
GET0000100002

增加list.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


${name}


如果在android中调用接口

增加权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

网络访问应该放在线程中


package com.myapplication;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    Runnable RestfulRun = new Runnable() {
        @Override
        public void run() {
// TODO Auto-generated method stub
            String URL = "http://192.168.9.160:8080/SpringMVC/RestfullAGet/00001";
            HttpURLConnection conn = null;
            try {
                URL target = new URL(URL);
                conn = (HttpURLConnection) target.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept", "application/json");
                if (200 != conn.getResponseCode()) {
                    throw new RuntimeException("failed, error code is " + conn.getResponseCode());
                }
                byte[] temp = new byte[conn.getInputStream().available()];
                if (conn.getInputStream().read(temp) != -1) {
                    Log.i("info", new String(temp));
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
                new Thread(RestfulRun).start();
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


你可能感兴趣的:(android,框架)