刚开始学习URL类,现在上头给我出了个题目:
做一个程序向某一个服务器提交数据,用GET POST方法都可以,就提交一个mobile参数的数据吧,用ie可以模拟,比如http://xx.xx.xx.xx/server.jsp?mobile=1365111111。然后服务器端收到你的消息mobile内容是1365111111。服务器端就是request.getParamter("mobile");客户端怎么实现呢?这还有个参考代码:
public static String send(String urlString) {
try {
String line = "";
String result = "";
URL url = new URL(urlString);
URLConnection uc = url.openConnection();
uc.setConnectTimeout(10 * 1000);
HttpURLConnection huc = (HttpURLConnection) uc;
huc.setConnectTimeout(10 * 1000);
huc.setRequestMethod("GET");
huc.setDoInput(true);
huc.setRequestProperty("Connection", "close");
String header = huc.getHeaderField("Content-Length");
int len = 100;
if (header != null) {
try {
len = Integer.parseInt(header);
} catch (Exception e1) {
}
}
byte bytes[] = new byte[len];
huc.getInputStream().read(bytes);
result = new String(bytes);
huc.disconnect();
if (result != null)
result.replaceAll("\0", "");
return result;
} catch (Exception e1) {
System.out.println("连接服务器出错:" + e1.getMessage());
return null;
}
}
做一个程序向某一个服务器提交数据,用GET POST方法都可以,就提交一个mobile参数的数据吧,用ie可以模拟,比如http://xx.xx.xx.xx/server.jsp?mobile=1365111111。然后服务器端收到你的消息mobile内容是1365111111。服务器端就是request.getParamter("mobile");客户端怎么实现呢?这还有个参考代码:
public static String send(String urlString) {
try {
String line = "";
String result = "";
URL url = new URL(urlString);
URLConnection uc = url.openConnection();
uc.setConnectTimeout(10 * 1000);
HttpURLConnection huc = (HttpURLConnection) uc;
huc.setConnectTimeout(10 * 1000);
huc.setRequestMethod("GET");
huc.setDoInput(true);
huc.setRequestProperty("Connection", "close");
String header = huc.getHeaderField("Content-Length");
int len = 100;
if (header != null) {
try {
len = Integer.parseInt(header);
} catch (Exception e1) {
}
}
byte bytes[] = new byte[len];
huc.getInputStream().read(bytes);
result = new String(bytes);
huc.disconnect();
if (result != null)
result.replaceAll("\0", "");
return result;
} catch (Exception e1) {
System.out.println("连接服务器出错:" + e1.getMessage());
return null;
}
}
try {
hc = (HttpConnection)Connector.open("http://xx.xx.xx.xx/server.jsp?mobile=1365111111");
hc.setRequestProperty("content-type", "text/html;charset=UTF-8");
int len= (int)hc.getLength();
System.out.println(len); }
catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if(hc!=null)
hc.close();
if(dis!=null)
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
看看API
hc = (HttpConnection)Connector.open("http://xx.xx.xx.xx/server.jsp?mobile=1365111111");
hc.setRequestProperty("content-type", "text/html;charset=UTF-8");
hc.getResponseMessage()