atgoingguoat 2010-10-30 15:46
浏览 712
已采纳

java 模拟HTTP doPost请求 设置参数

最近做一接口,要通过JAVA类请求SERVLET ,DOPOST方法.
不知道怎么把我的参数传过去.在网上找了几个例子.
都不行.
方法一:

[code="java"]

package com.3sfg.setvlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**

  • HTTP工具箱
  • @author leizhimin 2009-6-19 16:36:18
    */
    public final class HttpTookit {
    private static Log log = LogFactory.getLog(HttpTookit.class);

    /** 
     * 执行一个HTTP GET请求,返回请求响应的HTML 
     * 
     * @param url                 请求的URL地址 
     * @param queryString 请求的查询参数,可以为null 
     * @param charset         字符集 
     * @param pretty            是否美化 
     * @return 返回请求响应的HTML 
     */ 
    public static String doGet(String url, String queryString, String charset, boolean pretty) { 
            StringBuffer response = new StringBuffer(); 
            HttpClient client = new HttpClient(); 
            HttpMethod method = new GetMethod(url); 
            try { 
                    if (StringUtils.isNotBlank(queryString)) 
                            //对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串 
                            method.setQueryString(URIUtil.encodeQuery(queryString)); 
                    client.executeMethod(method); 
                    if (method.getStatusCode() == HttpStatus.SC_OK) { 
                            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); 
                            String line; 
                            while ((line = reader.readLine()) != null) { 
                                    if (pretty) 
                                            response.append(line).append(System.getProperty("line.separator")); 
                                    else 
                                            response.append(line); 
                            } 
                            reader.close(); 
                    } 
            } catch (URIException e) { 
                    log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e); 
            } catch (IOException e) { 
                    log.error("执行HTTP Get请求" + url + "时,发生异常!", e); 
            } finally { 
                    method.releaseConnection(); 
            } 
            return response.toString(); 
    } 
    
    /** 
     * 执行一个HTTP POST请求,返回请求响应的HTML 
     * 
     * @param url         请求的URL地址 
     * @param params    请求的查询参数,可以为null 
     * @param charset 字符集 
     * @param pretty    是否美化 
     * @return 返回请求响应的HTML 
     */ 
    public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) { 
            StringBuffer response = new StringBuffer(); 
            HttpClient client = new HttpClient(); 
            HttpMethod method = new PostMethod(url); 
            //设置Http Post数据 
            if (params != null) { 
                    HttpMethodParams p = new HttpMethodParams(); 
                    for (Map.Entry<String, String> entry : params.entrySet()) { 
                            p.setParameter(entry.getKey(), entry.getValue()); 
                    }
                    p.setParameter("abc", "efg");
                    method.setParams(p); 
            } 
            try { 
                    client.executeMethod(method); 
                    if (method.getStatusCode() == HttpStatus.SC_OK) { 
                            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); 
                            String line; 
                            while ((line = reader.readLine()) != null) { 
                                    if (pretty) 
                                            response.append(line).append(System.getProperty("line.separator")); 
                                    else 
                                            response.append(line); 
                            } 
                            reader.close(); 
                    } 
            } catch (IOException e) { 
                    log.error("执行HTTP Post请求" + url + "时,发生异常!", e); 
            } finally { 
                    method.releaseConnection(); 
            } 
            return response.toString(); 
    } 
    
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("parax", "123456");
            String y = doGet("http://127.0.0.1:8080/AIRP/servletTest", "xx=00", "GBK", true); 
            String z = doPost("http://127.0.0.1:8080/AIRP/servletTest?", map, "GBK", false); 
            System.out.println(y); 
            System.out.println(z); 
    } 
    

    }[/code]

POST 方法 ,我在servletJ里,取不知任何参数,请求帮助.
感谢.
方法二:
[code="java"]
private static String testPost(String MSG_ID,String MOBILE_NO,String CONTENT,
String SERVICE_ID,String PASS,String SP_CODE,String LINK_ID,
String FEE_TYPE,String FEE_CODE) throws IOException {

    URL url = new URL("http://127.0.0.1:8080/AIRP/servletTest");      
    URLConnection connection = url.openConnection();      

    connection.setDoOutput(true);        
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");      
    out.write("MSG_ID="+MSG_ID+"&MOBILE_NO="+MOBILE_NO+"&ACTION_ID=3"
            +"&SERVICE_ID=99&PASS=asdfasd"
            +"&SP_CODE=10625777&LINK_ID="); //向页面传递数据。post的关键所在!      
    // remember to clean up      
    out.flush();      
    out.close();      

    String sCurrentLine;      
    String sTotalString;      
    sCurrentLine = "";
    sTotalString = "";
    InputStream l_urlStream;
    l_urlStream = connection.getInputStream();      
    // 传说中的三层包装阿!      
    BufferedReader l_reader = new BufferedReader(new InputStreamReader(      
            l_urlStream));      
    while ((sCurrentLine = l_reader.readLine()) != null) {      
        sTotalString += sCurrentLine + "\r\n";      

    }      
    System.out.println(sTotalString); 
    return sTotalString;
}

[/code]

if (params != null) {
HttpMethodParams p = new HttpMethodParams();
for (Map.Entry entry : params.entrySet()) {
p.setParameter(entry.getKey(), entry.getValue());
}
p.setParameter("abc", "efg");
method.setParams(p);
}

这样不知道怎么取不到参数...

  • 写回答

3条回答 默认 最新

  • enet_java 2010-10-30 15:59
    关注

    因为没有做过这方面的需求,刚刚也搜索一下,发现有一篇文章涉及到了,LZ可以看看
    http://winhonourxzg.iteye.com/blog/461219

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1