Android端向服务器端发送JSON数据。服务器接受到数据后返回JSON信息。
Android效果图:
未点击“发送” 点击“发送”,获取数据
服务端效果图:
android代码:
<span style="font-size:14px;">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();
}
}
}</span>
服务器代码(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源码