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个回答

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

因为dopost可以通过doget来进行调用,所以你直接在http://127.0.0.1:8080/AIRP/servletTest?加上需要传的参数是不是也可以出传递?
MS 方法二就是这样来做的。 :roll:

[size=xx-large][code="java"]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);
} [/code][/size]
改成了[size=xx-large]
int index = 0;
if(params != null){
data = new NameValuePair[params.size()];
for(Map.Entry entry : params.entrySet()){
data[index++] = new NameValuePair(entry.getKey(),entry.getValue());
}
}
method.setRequestBody(data);[/size]

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐