Réponse HTTP au format JSON Usin Gjava
package service;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import cn.edu.thu.cv.util.Base64Image;
public class Client {
public static final String IP_ADDR = "***. ***. ***. ***";//The server address should be changed to the server's IP here
public static final int PORT = 12345;//Server port number
public static int register (String name, String imgPath, int opNum) {
String imgStr = Base64Image.GetImageStr (imgPath);//It converts the image information into base64 encoding
int isRegSuccess = 0;
while (true) {
Socket socket = null;
try {
//Create a stream socket and connect it to the specified port number on the specified host
socket = new Socket (IP_ADDR, PORT);
System.out.println ("Connection has been established");
//Send data to the server
Map <String, String> map = new HashMap <String, String> ();
map.put ("name", name);
map.put ("img", imgStr);
map.put ("op", opNum + "");
//Convert json to String type
JSONObject json = new JSONObject (map);
String jsonString = "";
jsonString = json.toString ();
//Convert String to byte []
//byte [] jsonByte = new byte [jsonString.length () + 1];
byte [] jsonByte = jsonString.getBytes ();
DataOutputStream outputStream = null;
outputStream = new DataOutputStream (socket.getOutputStream ());
System.out.println ("The length of the data sent is:" + jsonByte.length);
outputStream.write (jsonByte);
outputStream.flush ();
System.out.println ("Data transfer completed");
socket.shutdownOutput ();
//Read server-side data
DataInputStream inputStream = null;
String strInputstream = "";
inputStream = new DataInputStream (new BufferedInputStream (socket.getInputStream ()));
strInputstream = inputStream.readUTF ();
System.out.println ("The input information is:" + strInputstream);
JSONObject js = new JSONObject (strInputstream);
System.out.println (js.get ("isSuccess"));
isRegSuccess = Integer.parseInt ((String) js.get ("isSuccess"));
//Disconnect if you receive "OK"
if (js! = null) {
System.out.println ("The client will close the connection");
Thread.sleep (500);
break;
}
} catch (Exception e) {
System.out.println ("Client exception:" + e.getMessage ());
break;
} finally {
if (socket! = null) {
try {
socket.close ();
} catch (IOException e) {
socket = null;
System.out.println ("Client finally exception:" + e.getMessage ());
}
}
}
}
return isRegSuccess;
}
public static void main (String [] args) {
register ("gongyunfei", "D:/test1.jpg", 1);//The third parameter is the type of operation server can know what you are doing
}
}
Blue-eyed Bug