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

Java 后台模拟发送 POST GET 请求

2015-04-07 17:20 841 查看
1.通过get方式传递服务器数据

/**
* 发送GET请求
* @param path 请求路径
* @param params 请求参数
* @param encoding 编码
* @return 请求是否成功
*/
private static boolean sendGETRequest(String path, Map<String, String> params, String ecoding) throws Exception{
// http://192.168.1.100:8080/web/ManageServlet?title=xxx&timelength=90 StringBuilder url = new StringBuilder(path);
url.append("?");
for(Map.Entry<String, String> entry : params.entrySet()){
url.append(entry.getKey()).append("=");
url.append(URLEncoder.encode(entry.getValue(), ecoding));
url.append("&");
}
url.deleteCharAt(url.length() - 1);
HttpURLConnection conn = (HttpURLConnection)new URL(url.toString()).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
return true;
}
return false;
}


2.通过post方式传递数据

/**
* 发送Post请求
* @param path 请求路径
* @param params 请求参数
* @param encoding 编码
* @return 请求是否成功
*/
private static boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{
//  title=liming&timelength=90
StringBuilder data = new StringBuilder();
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
data.append(entry.getKey()).append("=");
data.append(URLEncoder.encode(entry.getValue(), encoding));
data.append("&");
}
data.deleteCharAt(data.length() - 1);
}
byte[] entity = data.toString().getBytes();//生成实体数据
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);//允许对外输出数据
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(entity);
if(conn.getResponseCode() == 200){
return true;
}
return false;
}


3.通过HttpClient发送Post请求

/**
* 保存数据
* @param title 标题
* @param length 时长
* @return
*/
public static boolean save(String title, String length) {
String path = "http://192.168.0.208:8080/web/ManageServlet";
Map<String, String> params = new HashMap<String, String>();
params.put("title", title);
params.put("timelength", length);
try {
return sendHttpClientPOSTRequest(path, params, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 通过HttpClient发送Post请求
* @param path 请求路径
* @param params 请求参数
* @param encoding 编码
* @return 请求是否成功
*/
private static boolean sendHttpClientPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{
List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放请求参数
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(entity);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200){
return true;
}
return false;
}

4.上述发送的都是byte 但是生成的参数接受方式还是request.getParameter("key")

4.下面发送的都是json xml btye流 注意下面的接收写法 第5点写的是发送


@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
InputStream in = req.getInputStream();
try {
byte[]b=this.read(in);
System.out.println(new String(b));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}


5.发送xml数据给web应用

public void testSendXML() throws Exception{
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("person.xml");
byte[] data = this.read(inStream);
System.out.println( String.valueOf(data.length));
String path = "http://192.168.0.102:8080/web/XmlServlet";
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.getOutputStream().write(data);
if(conn.getResponseCode() == 200){
System.out.println("发送成功");
}else{
System.out.println("发送失败");
}
}
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) != -1){
outputStream.write(buffer, 0, len);
}
inStream.close();
return outputStream.toByteArray();
}
//接受数据
byte[] data = StreamTool.read(request.getInputStream());
            String xml = new String(data, "UTF-8");
            System.out.println(xml);
在StreamTool这个类中,
ByteArrayOutputStream
可以将输入的流转化为byte类型,从而达到转化为String类型的数据格式,但是像以前从url中读取到的数据,直接就可以拼写出来,这是因为本次在发送的时候呢,发送的格式就是byte类型的数据.

****重点解析****

在上面的结构中conn.getResponseCode()==200之后,进行的操作都是基于服务器发布数据的时候,调用了输出流,并在输出流中写入了数据,而前面的每日一句的写法中,是在后台这样写的

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

System.out.println("protected");
req.setCharacterEncoding("utf-8");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Cache-Control", "no-store");
resp.setContentType("application/xml; charset=utf-8");
PrintWriter out = resp.getWriter();
/**
* OutputStream 只能输入二进制数据;
*/
//		OutputStream ops = resp.getOutputStream();
out.print(new XmlServlet().getXmlInfo());
out.flush();
out.close();
}
private String getXmlInfo() {
    StringBuilder sb = new StringBuilder();
    sb.append("<videoSend>");
    sb.append("<header>");
    sb.append("<sid>1</sid>");
    sb.append("<type>service</type>");
    sb.append("</header>");
    sb.append("<service name=\"videoSend\">");
    sb.append("<fromNum>0000021000011001</fromNum>");
    sb.append("<toNum>33647405</toNum>");
    sb.append("<videoPath>mnt/5.0.217.50/resources/80009.mov</videoPath>");
    sb.append("<chargeNumber>0000021000011001</chargeNumber>");
    sb.append("</service>");
    sb.append("</videoSend>");
    return sb.toString();
}
这样的数据,发布在页面是直接就是xml的格式,所以在读取的时候是不需要conn.getResponseCode()==200来获得输入流的,直接将输入流读取成字符串即可,而当你写入别的东西,比如二进制字节时,则用到了输出流和byte的转化
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息