您的位置:首页 > 编程语言 > Java开发

java,用post方法提交数据,并且从服务器返回结果。

2014-08-07 10:16 375 查看
一下是客户端的代码:

//使用post向服务器提交数据。
public class HttpUtil {

//private static String Path = "http://172.17.32.86:8080/TestServer/servlet/testServlet";
private static String Path = "http://192.168.3.2:8080/TestServer/servlet/testServlet";

private static URL url;

public HttpUtil() {

}

static {
try {
url = new URL(Path);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static String sendPostMessage(Map<String, String> params,
String encode) {
StringBuffer sb = new StringBuffer();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
try {
sb.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sb.deleteCharAt(sb.length() - 1);// 删除最后一个&
System.out.println(sb.toString());
try {
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(3000);
connection.setDoInput(true);// 表示从服务器获取数据
connection.setDoOutput(true);// 表示想服务器写入数据
byte[] data = sb.toString().getBytes();// 字符数字变成字节数组
// 表示设置的请求体是文本类型
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
String.valueOf(data.length));
//获得输出流,向服务器输出数据
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data);
int code = connection.getResponseCode();
if (code == 200) {
System.out.println("code====="+code);
return changeInputStream(connection.getInputStream(),
encode);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "";
}

/**
* 将一个输入流转换为指定编码的字符串
*
* @param inputStream
* @param encode
* @return
*/
private static String changeInputStream(InputStream inputStream,
String encode) {
// TODO Auto-generated method stub
//创建一个内存字节流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result=null;
if (inputStream != null) {
try {
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
//将字节转换为字符串
result = new String(outputStream.toByteArray(), encode);
System.out.println("result=============="+result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return result;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "1234");
sendPostMessage(params, "utf-8");
}

}


一下是服务器端的servlet,以上是客户端把数据提交给了这个servlet。
public class testServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String usernameString = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("=========" + password);
if (usernameString.equals("admin") && password.equals("1234")) {
out.print("login success");
}
out.close();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doGet(request, response);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  csdn博客 程序员
相关文章推荐