一些变量的定义:
//需要将下面的IP改为服务器端IP
private String txtUrl = "http://192.168.1.46:8080/AppServer/SynTxtDataServlet";
private String url = "http://192.168.1.46:8080/AppServer/SynDataServlet";
private String uploadUrl = "http://192.168.1.46:8080/AppServer/UploadFileServlet";
private String fileUrl = "http://192.168.1.46:8080/AppServer/file.jpg";
private String txtFileUrl = "http://192.168.1.46:8080/AppServer/txtFile.txt";
NetTool类,实现功能
public class NetTool {
private static final int TIMEOUT = 10000;// 10秒
/**
* 传送文本,例如Json,xml等
*/
public static String sendTxt(String urlPath, String txt, String encoding)
throws Exception {
byte[] sendData = txt.getBytes();
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(TIMEOUT);
// 如果通过post提交数据,必须设置允许对外输出数据
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Charset", encoding);
conn.setRequestProperty("Content-Length", String
.valueOf(sendData.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(sendData);
outStream.flush();
outStream.close();
if (conn.getResponseCode() == 200) {
// 获得服务器响应的数据
BufferedReader in = new BufferedReader(new InputStreamReader(conn
.getInputStream(), encoding));
// 数据
String retData = null;
String responseData = "";
while ((retData = in.readLine()) != null) {
responseData += retData;
}
in.close();
return responseData;
}
return "sendText error!";
}
/**
* 上传文件
*/
public static String sendFile(String urlPath, String filePath,
String newName) throws Exception {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
URL url = new URL(urlPath);
HttpURLConnect