簡體   English   中英

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

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

我沒有以下任何一種工作:

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工作?

流暢的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM