由于本次笔记是在本机上执行的,所以安装了appache的tomcat服务器,首先认识一下,servlet类,这个类是在tomcat服务器里面进行协议的,tomcat属于协议里面的应用层吧,所以和路由器里面的那层没什么重要的联系,本次是在本机上执行的,因为要进行访问,所以我的手机终端要用到的网管是路由器里面的默认网关,而我的路由器可以发送wifi网络,网关和电脑连接的网关是一致的,所以网络是没有问题的,接下来的问题就是http协议的具体流程了,java里面的tomcat服务器是可以直接加载servlet类的,浏览器可以正常访问,说明servelt的http协议是通的,因为本次用的是post请求数据的,又是传递json数据的,java读取客户端发送过来的消息都是通过流来接受的,所以传递json数据也是通的,接下来就是字符编码的问题了,客户端发送的中文到tomcat这边来默认的不是utf-8,所以servlet在接受客户端发送过来的请求时候需要设置一下接受的字符编码了,这客户端发送的请求已经接收了,现在就是要给客户端发送数据了,不知道什么问题,反正一开始我客户端接受的数据不论怎么解码,编码都是乱码,最终确认了让tomcat默认发送消息头是默认的编码,然后客户端这边用tomcat默认的字符编码解码,然后再编码,乱码问题解决了;现在来看看截图
1.查看本地网络配置
服务端的代码:
package com.android.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
import netscape.javascript.JSObject;
/**
* Servlet implementation class AndroidServlet
*/
@WebServlet(urlPatterns = "/Login", name = "AndroidServlet", initParams = {
@WebInitParam(name = "name", value = "huangxudong"), @WebInitParam(name = "pass", value = "123456") })
public class AndroidServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AndroidServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response){
// TODO Auto-generated method stub
String nString=response.getContentType();
StringBuffer stringBuffer = new StringBuffer();
String name = null;
String pass = null;
InputStream inputStream = null;
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
inputStream = request.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] bs = new byte[1024];
int length;
try {
while ((length = inputStream.read(bs)) != -1) {
stringBuffer.append(new String(bs, 0, length,"UTF-8"));
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (stringBuffer != null) {
JSONObject jsonObject = new JSONObject(stringBuffer);
try {
name = jsonObject.getString("username");
pass = jsonObject.getString("password");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (name != null && pass != null) {
if (name.equals(getInitParameter("name")) && pass.equals(getInitParameter("pass"))) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("msg", "112");
jsonObject.put("date", new Date());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new String(jsonObject.toString().getBytes(),"UTF-8"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("msg", "123啊是");
jsonObject.put("date", new Date());
response.getWriter().write(jsonObject.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
由于是进行测试,所以代码质量没有在意..
再来看android端的代码:
package www.hubei.servlet.myapplication;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputEditText mTextInputEditText,mTextInputEditText1;
private Button mButton,mButton1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextInputEditText= (TextInputEditText) findViewById(R.id.et_username);
mTextInputEditText1= (TextInputEditText) findViewById(R.id.et_userpass);
mButton= (Button) findViewById(R.id.btn_get);
mButton1= (Button) findViewById(R.id.btn_post);
mButton.setOnClickListener(this);
mButton1.setOnClickListener(this);
}
private void doPost(String username,String password) throws IOException, JSONException {
if (mTextInputEditText.getText().toString().isEmpty()||mTextInputEditText.getText().toString().equals(null)){
Toast.makeText(this, "用户名不能为空!!!", Toast.LENGTH_SHORT).show();
return;
}
if (mTextInputEditText1.getText().toString().isEmpty()||mTextInputEditText1.getText().toString().equals(null)){
Toast.makeText(this, "用户名密码不能为空!!!", Toast.LENGTH_SHORT).show();
return;
}
URL url=new URL("http://10.0.2.2:8080/TestHttp/Login");
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(4000);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
OutputStream outputStream=httpURLConnection.getOutputStream();
JSONObject jsonObject=new JSONObject();
jsonObject.put("username",username);
jsonObject.put("password",password);
String url1=new String(jsonObject.toString().getBytes(),"UTF-8");
StringBuffer stringBuffer=new StringBuffer();
outputStream.write(url1.getBytes());
outputStream.flush();
if (200==httpURLConnection.getResponseCode()){
InputStream inputStream=httpURLConnection.getInputStream();
InputStreamReader streamReader=new InputStreamReader(inputStream,"iso8859-1");
char []bytes=new char[1024];
int length;
while ((length=streamReader.read(bytes))!=-1){
stringBuffer.append(new String(bytes,0,length));
}
}
Log.e("aaa", new String(stringBuffer.toString().getBytes("iso8859-1"),"UTF-8"));
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_get:
break;
case R.id.btn_post:
new Thread(){
@Override
public void run() {
super.run();
try {
doPost(mTextInputEditText.getText().toString(),mTextInputEditText1.getText().toString());
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
break;
}
}
}
由于最后我要在模拟器上进行测试,所以主机地址改成了android模拟器默认的ip地址,这都是要注意的哦。
最后还说下,用谷歌浏览器的开发者工具,可以对web前端进行抓包,然后进行分析,协议分:协议头和body体的,客户端发送http协议请求都是要设置协议头的,服务器返回的时候也是要设置协议头的,具体的协议头可以在开发者工具中查看,顺便截图一下谷歌的开发者工具: