doget方式
String urlString = "http://localhost:8080/MyWebApp/MyServlet?username=张三&password=123456";
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setConnectTimeout(3000);
httpConnection.setReadTimeout(3000);
int code =httpConnection.getResponseCode();
System.out.println("http状态码:"+code);
if(code==HttpURLConnection.HTTP_OK){
InputStream is= httpConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch(SocketTimeoutException e){
System.out.println("网络连接超时");
} catch (IOException e) {
e.printStackTrace();
}
dopost方式
String urlString = "http://localhost:8080/WebServer/MyServletJSON";
try {
URL url = new URL(urlString);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
/**
* post和get的不同点
*/
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setUseCaches(false);
/**
*
*/
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
/**
* 设置向服务器提交的参数
*/
String params = "jsoncontent=zhangsan";
httpConnection.getOutputStream().write(params.getBytes());
int code = httpConnection.getResponseCode();
System.out.println(code);
if(code==HttpURLConnection.HTTP_OK){
InputStream is = httpConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line!=null){
System.out.println(line);
line = br.readLine();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}