import org.apache.http HttpPost()。getParams()。setParameter(...)不工作,也不是HttpPost()。setEntity(list)

时间:2014-08-06 15:10:25

标签: java apache

我没有得到以下任何一种方法:

import import org.apache.http....

    HttpPost post = new HttpPost(new URI(url));

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    HttpParams postP = post.getParams();
    for ( String param : postParams.keySet() ) {
        String value = postParams.get( param );
        postP.setParameter( param, value );    // one way to set POST vals
        // params.add( new BasicNameValuePair( param, value) );  // alt way to set post vals?
    }
    // post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));  // alt way to set post vals?

    // transfer Access token to HTTP header
    if ( access_token != null ) {
        post.setHeader( "access_token", access_token );
    }

    HttpResponse response = sslClient.execute( post );

对于setParameter()或setEntity()方法,Web服务器不记录任何内容。例如,Google+(https://accounts.google.com/o/oauth2/token)回复说未设置所需的参数。

然而以下工作,但恕我直言是纯粹的凌乱;我更喜欢上述之一:

    URL uri = new URL(url);
    URLConnection conn = uri.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    StringBuilder sb = new StringBuilder();
    for ( String param : postParams.keySet() ) {
        String value = postParams.get( param );
        sb.append(param +"="+ value +"&");
    }
    //write parameters
    writer.write( sb.toString() );
    writer.flush();

什么方法可以让纯粹的org.apache.http工作?

1 个答案:

答案 0 :(得分:0)

流畅的API使用户无需处理系统的手动释放 在某些情况下,必须以内存缓冲响应内容为代价的资源。

Request.Get("http://targethost/homepage")
    .execute().returnContent();
Request.Post("http://targethost/login")
    .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())
    .execute().returnContent();

链接到javadoc:http://hc.apache.org/httpcomponents-client-ga/fluent-hc/apidocs/org/apache/http/client/fluent/Request.html