Android开发之与服务器(jsp)发送、接受JSON数据
16lz
2021-01-23
Android端向服务器端发送JSON数据。服务器接受到数据后返回JSON信息。
Android效果图:
未点击“发送” 点击“发送”,获取数据
服务端效果图:
android代码:
public class MainActivity extends AppCompatActivity { //地址,请根据自己的地址设置 public final static String MyURL = "http://192.168.1.100:8080/JsonDeal/Deal"; private Button but; private TextView tv; private JSONObject object; Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); but = (Button) this.findViewById(R.id.but); tv = (TextView) this.findViewById(R.id.tv); try { object = new JSONObject(); object.put("client", "我是客户端来的"); } catch (JSONException e) { e.printStackTrace(); } but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread() { @Override public void run() { super.run(); submit(); } }.start(); } }); } public void submit() { try { URL url = new URL(MyURL); HttpURLConnection 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(object.toString(), "UTF-8").getBytes()); // 如果请求响应码是200,则表示成功 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { //获取服务器上的数据 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); try { //解码 String jsonStr = URLDecoder.decode(in.readLine(), "UTF-8"); final JSONObject objectT = new JSONObject(jsonStr); Log.i("objectT", objectT.getString("server")); //更新TextView组件 handler.post(new Runnable() { @Override public void run() { try { tv.setText(objectT.getString("server")); } catch (JSONException e) { e.printStackTrace(); } } }); } catch (JSONException e) { e.printStackTrace(); } in.close(); conn.disconnect(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (SocketTimeoutException e) { handler.post(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "连接超时", Toast.LENGTH_SHORT).show(); return; } }); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
服务器代码(jsp)
Deal.java
public class Deal extends HttpServlet {public Deal() {super();}public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");//获取数据InputStream inputStream = request.getInputStream();String json = NetUtils.readString(inputStream);json = URLDecoder.decode(json, "UTF-8");JSONObject jsonT = JSONObject.fromObject(json);System.out.println(jsonT.getString("client"));JSONObject jsonObject = new JSONObject();jsonObject.put("server", "我从服务器来");String serverStr = URLEncoder.encode(jsonObject.toString(), "UTF-8");//发送数据PrintWriter printWriter = response.getWriter();printWriter.write(serverStr);}public void init() throws ServletException {// Put your code here}}
NetUtils.java
import java.io.ByteArrayOutputStream;import java.io.InputStream;public class NetUtils {public static byte[] readBytes(InputStream is) {try {byte[] buffer = new byte[1024];int len = -1;ByteArrayOutputStream baos = new ByteArrayOutputStream();while ((len = is.read(buffer)) != -1) {baos.write(buffer, 0, len);}baos.close();return baos.toByteArray();} catch (Exception e) {e.printStackTrace();}return null;}public static String readString(InputStream is) {return new String(readBytes(is));}}
源码:
android源码(android studio)和jsp源码
更多相关文章
- Android之使用Pull解析Xml数据
- Android RIL源码分析(2)
- android SQLite数据库2
- Android 创建SQLite数据库(一)
- Android利用wireshark抓取网络数据包
- [置顶] Android上传文件到Web服务器,PHP接收文件(二)
- Android 中数据库查询方法 query() 中的 selectionArgs 的用法
- Android视频播放器源码
- Android预安装软件&adb命令&编译源码