简体   繁体   English

导入org.apache.http HttpPost()。getParams()。setParameter(…)无效,HttpPost()。setEntity(list)也无效

[英]import org.apache.http HttpPost().getParams().setParameter(…) not working, nor is HttpPost().setEntity(list)

I not getting either of the following to work: 我没有以下任何一种工作:

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 );

for either the setParameter() or setEntity() methods, the web server logs nothing. 对于setParameter()或setEntity()方法,Web服务器什么都不记录。 for example Google+ ( https://accounts.google.com/o/oauth2/token ) replies that required params are not set. 例如Google+( https://accounts.google.com/o/oauth2/token )答复未设置必需的参数。

However the following works but IMHO is pure messy; 但是,以下方法可以解决,但是恕我直言,这是一团糟。 i'd prefer one of the above: 我更喜欢上面的一种:

    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();

any way to get the pure org.apache.http to work? 有什么办法可以使纯org.apache.http工作?

The fluent API relieves the user from having to deal with manual deallocation of system resources at the cost of having to buffer response content in memory in some cases. 流畅的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();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM