java搭建本地服务器,android客户端访问,tomcat详细步骤
代码都在这里,先可以不用下这个,跟着下面先把环境搭好,出问题再来看代码:
https://download.csdn.net/download/qq_31939617/10275515eclispe64位,直接解压就可以用
https://pan.baidu.com/s/1nwv1JM5
jdk配置就自行百度吧
Tomcat安装:
1.任意打开一个浏览器,搜索tomcat。在结果列表中打开tomcat官网。
https://tomcat.apache.org/download-80.cgi
往下拉,找到8.0版本的(最好是用为0的版本,6.0/7.0/8.0,刚开始时候装了个8.5.28版本,在后面eclispe配置出现问题了)
2.安装版本的,点击安装
3.选择jre位置(jdk先装了吧)
4.选择安装位置
5.安装完成了
6.安装版有3种启动服务的方法。
一是打开bin目录下的Tomcat8w.exe;
二是计算机——>管理——>服务(管理tomcat的服务);
三是通过任务栏上的tomcat启动图标管理tomcat的启动和暂停
启动成功
7.在浏览器输入:http://localhost:8080/,出现这个页面Tomcat安装就完成了
下面为eclipse配置tomcat
1.打开eclipse--Windows--Preferences,选择
2.选择tomcat版本,我安装的是8.0的
3.选择tomcat,jre路径
创建项目:
2.项目新建完成,自行导入servlet库(项目属性->Build Path->add Libraries),安装了tomact也有这个。
都放这了,包括mysql,json的
https://download.csdn.net/download/qq_31939617/10274249
放到lib里面,别忘了右键Buil path--Add to Buil path
2.在src下新䢖abc包,下面新建Test.class
package abc;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class Test extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map
map.put("code", "200");
map.put("msg", "");
Map
map1.put("version", "2.1.0");
map1.put("describe", "1.优化网络加载速度");
map.put("data", map1);
// 无参请求
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONObject obj = JSONObject.fromObject(map);
out.write(obj.toString());
return;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3.在根目录WEB-INF/web.xml,
服务端完成
使用android stduio 创建简单的工程。访问上面创建的servlet,如果是真机,需要改localhost为pc的IP地址。
别忘了权限:
<uses-permission android:name="android.permission.INTERNET"/>
清单文件:AndroidManifest.xml
xml version="1.0" encoding="utf-8"?>xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sz.test"> android:name="android.permission.INTERNET"/> android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> android:name=".MainActivity"> android:name="android.intent.action.MAIN" /> android:name="android.intent.category.LAUNCHER" />
布局文件:activity_main.xml可以复制:
xml version="1.0" encoding="utf-8"?>xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context="com.example.sz.test.MainActivity">
MainAcitvity.class可以复制:
package com.example.sz.test; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.json.JSONObject; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; TextView tv; Button btn; public static final int MSG_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = findViewById(R.id.tv); btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Map, Object> map = new HashMap<>(); //map.put("mobile", phone); String url = "http://192.168.1.194:8080/Te/abc_test"; HttpClientUtil.postRequestNetwork(url, map, false, new HttpClientUtil.HttpClientCallbackListener() { @Override public void onSuccess(String response) { Log.e(TAG, "onSuccess: -------------" + response); // {"code":"200","msg":"","data":{"version":"2.0.1","describe", "1.优化网络加载速度"}} JSONObject jsonObject1 = null; JSONObject jsonObject2 = null; Log.e(TAG, "onSuccess: --response--" + response); //json解析取出返回值 try { jsonObject1 = new JSONObject(response); int code = jsonObject1.getInt("code"); jsonObject2 = jsonObject1.getJSONObject("data"); String version = jsonObject2.getString("version"); String describe = jsonObject2.getString("describe"); Message message = new Message(); message.what = MSG_CODE; Bundle bundle = new Bundle(); bundle.putInt("code", code); bundle.putString("version", version); bundle.putString("describe", describe); message.setData(bundle); mHandler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "onSuccess: --e---" + e); } } @Override public void onFailure(Exception e) { Log.e(TAG, "onFailure: -----e------" + e); } }); } }); } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_CODE: int code = msg.getData().getInt("code"); String version = msg.getData().getString("version");//读出数据 String describe = msg.getData().getString("describe");//读出数据 if (code == 200) { tv.setText("code:"+code + "version:"+version +"describe:"+ describe); } break; default: break; } } }; }
HttpClientUtil.class可以复制:
package com.example.sz.test; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; /** * Created by ThinkPad on 2017/8/20. * HttpClientUtil工具类 * lib下导入org.apache.http.legacy.jar */ public class HttpClientUtil { private static final String TAG = "HttpClientUtil"; private static String response = ""; //get请求服务器 public static void getRequestNetwork(final String urlPath, final HttpClientCallbackListener listener) { new Thread(new Runnable() { @Override public void run() { try { HttpGet getMethod = new HttpGet(urlPath);//将URL与参数拼接 HttpClient httpClient = new DefaultHttpClient(); HttpResponse mHttpResponse = httpClient.execute(getMethod); //发起GET请求 int code = mHttpResponse.getStatusLine().getStatusCode(); if (code == 200) { response = EntityUtils.toString(mHttpResponse.getEntity(), "utf-8"); Log.e(TAG, "getRequestNetwork:---- " + response); if (listener != null) { listener.onSuccess(response.toString()); } } } catch (IOException e) { e.printStackTrace(); if (listener != null) { listener.onFailure(e); } } } }).start(); } /** * 通过post请求服务器 * * @param url * @param params 参数 * @param skipNull 是否跳过NULL值,true则不发送value=null的key,否则发送value= * 需要导入lib中的jar包 */ public static void postRequestNetwork(final String url, final Map, Object> params, final boolean skipNull, final HttpClientCallbackListener listener) { new Thread(new Runnable() { @Override public void run() { OutputStreamWriter out = null; BufferedReader in = null; StringBuilder connResult = new StringBuilder(""); String fullUrl = ""; try { StringBuilder builder = new StringBuilder(); if (null != params && params.size() > 0) { for (String s : params.keySet()) { if (null == params.get(s)) { if (!skipNull) { builder.append(s).append("=").append("&"); } continue; } if (params.get(s) instanceof Iterable>) { Iterable> ite = (Iterable>) params.get(s); for (Object i : ite) { builder.append(s).append("=").append(i).append("&"); } } else { builder.append(s).append("=").append(params.get(s)).append("&"); } } builder.delete(builder.length() - 1, builder.length()); } fullUrl = url + "?" + builder.toString(); // log.debug(String.format("http request %s", fullUrl)); URL destURL = new URL(url); HttpURLConnection urlConn = (HttpURLConnection) destURL.openConnection(); urlConn.setConnectTimeout(5000); urlConn.setReadTimeout(40000); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setAllowUserInteraction(false); urlConn.setUseCaches(false); urlConn.setRequestMethod("POST"); OutputStream oups = urlConn.getOutputStream(); oups.write(builder.toString().getBytes()); urlConn.connect(); // 响应编码 String contentType = urlConn.getHeaderField("Content-Type"); String encode = "UTF-8"; int index = -1; if (null != contentType && (index = contentType.indexOf("charset=")) > -1) { encode = contentType.substring(index + 8); } // 返回状态码 int state = urlConn.getResponseCode(); if (state < 400) {// 返回状态码<400为正确响应 in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), encode)); } else { in = new BufferedReader(new InputStreamReader(urlConn.getErrorStream(), encode)); } String s = null; while ((s = in.readLine()) != null) { connResult.append(s); } // log.debug(String.format("http request %s, response[code:%d, encode:%s, content:%s]", fullUrl, state, // encode, connResult.toString())); if (listener != null) { listener.onSuccess(connResult.toString()); } } catch (IOException e) { e.printStackTrace(); // log.error("http request[" + fullUrl + "] error", e); if (listener != null) { listener.onFailure(e); } } finally { try { if (out != null) { out.close(); if (in != null) { in.close(); } } } catch (IOException e) { e.printStackTrace(); } } } }).start(); } public interface HttpClientCallbackListener { void onSuccess(String response); void onFailure(Exception e); } }
记着引入httpClient
真机测试 ,一定要在同一局域网内,要把这个地址换成自己的
成功
代码都在这里:
https://download.csdn.net/download/qq_31939617/10275515