我有一个Android客户端,它将JSON对象发送到服务器(REST服务)。 我的客户端使用urlconnection连接到我服务器端的Web服务。
代码工作正常! 我的服务器端是使用NetBeans上的GlassFish服务器的Java类Web服务。
由于我是客户服务器主题的新手 - 我有几个问题:
客户端(ANDROID): AsyncTask-> doInBackground - >尝试
try {
JSONObject jsonObject = new JSONObject("string");
// Step2: Now pass JSON File Data to REST Service
try {
URL url = new URL("http://localhost:8080/w/JSONService");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonObject.toString());
out.close();
//string answer from server:
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
System.out.println("\n"+line);
in.close();
} catch (Exception e) {
System.out.println("\nError while calling JSON REST Service");
System.out.println(e);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
} } }
服务器(JAVA):
@Path("/w")
public class JSONRESTService {
String returned;
@POST
@Consumes("application/json")
@Path("/JSONService")
public String JSONREST(InputStream incomingData) {
StringBuilder JSONBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
JSONBuilder.append(line);
} returned ="transfer was completed";
} catch (Exception e) {
System.out.println("Error Parsing: - ");
returned ="error";
}
System.out.println("Data Received: " + JSONBuilder.toString());
return (returned);
}
}