2010-06-02 33 views
115

Tôi có một yêu cầu HTTP GET mà tôi đang cố gắng gửi. Tôi đã thử thêm các tham số cho yêu cầu này bằng cách đầu tiên tạo một đối tượng BasicHttpParams và thêm các tham số cho đối tượng đó, sau đó gọi setParams(basicHttpParms) trên đối tượng HttpGet của tôi. Phương pháp này không thành công. Nhưng nếu tôi thêm thông số của mình vào URL của tôi theo cách thủ công (ví dụ: nối thêm ?param1=value1&param2=value2) thì thành công.Cách thêm thông số vào yêu cầu HTTP GET trong Android?

Tôi biết tôi thiếu điều gì đó ở đây và mọi trợ giúp sẽ được đánh giá cao.

+1

Đối với yêu cầu GET, phương pháp thứ hai là cách chính xác để thêm thông số. Tôi hy vọng cách tiếp cận đầu tiên là cho phương thức POST. –

Trả lời

223

Tôi sử dụng Danh sách NameValuePair và URLEncodedUtils để tạo chuỗi url tôi muốn.

protected String addLocationToUrl(String url){ 
    if(!url.endsWith("?")) 
     url += "?"; 

    List<NameValuePair> params = new LinkedList<NameValuePair>(); 

    if (lat != 0.0 && lon != 0.0){ 
     params.add(new BasicNameValuePair("lat", String.valueOf(lat))); 
     params.add(new BasicNameValuePair("lon", String.valueOf(lon))); 
    } 

    if (address != null && address.getPostalCode() != null) 
     params.add(new BasicNameValuePair("postalCode", address.getPostalCode())); 
    if (address != null && address.getCountryCode() != null) 
     params.add(new BasicNameValuePair("country",address.getCountryCode())); 

    params.add(new BasicNameValuePair("user", agent.uniqueId)); 

    String paramString = URLEncodedUtils.format(params, "utf-8"); 

    url += paramString; 
    return url; 
} 
+0

Tôi đồng ý. Tôi đã quay lại và thay đổi điều này vì phương pháp này có ý nghĩa đối với số lượng thông số lớn hơn. Câu trả lời được chấp nhận đầu tiên vẫn hoạt động tốt, nhưng có thể gây nhầm lẫn cho các tập hợp thông số lớn. – groomsy

+0

@ Brian Griffey Cảm ơn bạn đã giải pháp tốt. nhưng tôi có ít định dạng khác nhau để vượt qua tham số, Bất cứ ai có thể giúp tôi vượt qua tham số này ..? Cách chuyển tham số trong trường hợp này? data = '{ "chứng chỉ": { "accesToken": "668f514678c7e7f5e71a07044935d94c", "ACK": "cf3bb509623a8e8fc032a08098d9f7b3" }, "restIn": { "userId": 4, "listId": 5613 } }; –

+2

chính xác là tuyệt đối, không có gì để leo thang :). Câu trả lời hay vì nhiều lý do. – sschrass

27

Phương pháp

setParams() 

như

httpget.getParams().setParameter("http.socket.timeout", new Integer(5000)); 

chỉ thêm HttpProtocol tham số.

Để thực hiện httpGet bạn nên thêm vào thông số của bạn vào url bằng tay

HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar"); 

hoặc sử dụng các yêu cầu bài sự khác biệt giữa GET và POST yêu cầu được giải thích here, nếu bạn quan tâm

+1

Cảm ơn sự giúp đỡ của bạn. Tôi nghĩ rằng có thể có một cách hiệu quả hơn để thêm các tham số vào các yêu cầu GET. – groomsy

91

Để xây dựng uri với các tham số, Uri.Builder cung cấp một cách hiệu quả hơn.

Uri uri = new Uri.Builder() 
    .scheme("http") 
    .authority("foo.com") 
    .path("someservlet") 
    .appendQueryParameter("param1", foo) 
    .appendQueryParameter("param2", bar) 
    .build(); 
+1

Quá tệ, nó không thể xử lý số cổng. Nếu không thì câu trả lời tốt. –

+37

'Uri.Builder b = Uri.parse (" http://www.site.com:1234 ") .buildUpon();' cũng hoạt động – Merlin

+0

Cũng không thể xử lý thông số tệp – siamii

8
List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("param1","value1"); 

String query = URLEncodedUtils.format(params, "utf-8"); 

URI url = URIUtils.createURI(scheme, userInfo, authority, port, path, query, fragment); //can be null 
HttpGet httpGet = new HttpGet(url); 

URI javadoc

Lưu ý: url = new URI(...) là buggy

28

Tính đến HttpComponents4.2+ có một lớp mới URIBuilder, cung cấp cách thuận tiện để tạo ra các URI.

Bạn có thể sử dụng hoặc tạo URI trực tiếp từ chuỗi URL:

List<NameValuePair> listOfParameters = ...; 

URI uri = new URIBuilder("http://example.com:8080/path/to/resource?mandatoryParam=someValue") 
    .addParameter("firstParam", firstVal) 
    .addParameter("secondParam", secondVal) 
    .addParameters(listOfParameters) 
    .build(); 

Nếu không, bạn có thể chỉ định tất cả các thông số một cách rõ ràng:

URI uri = new URIBuilder() 
    .setScheme("http") 
    .setHost("example.com") 
    .setPort(8080) 
    .setPath("/path/to/resource") 
    .addParameter("mandatoryParam", "someValue") 
    .addParameter("firstParam", firstVal) 
    .addParameter("secondParam", secondVal) 
    .addParameters(listOfParameters) 
    .build(); 

Khi bạn đã tạo URI đối tượng, sau đó bạn chỉ đơn giản là cần để tạo đối tượng HttpGet và thực hiện:

//create GET request 
HttpGet httpGet = new HttpGet(uri); 
//perform request 
httpClient.execute(httpGet ...//additional parameters, handle response etc. 
+1

Điều này nên là câu trả lời hàng đầu, tôi không biết làm thế nào mà người được chọn có 200 upvotes và cái này chỉ có 20. –

4
HttpClient client = new DefaultHttpClient(); 

    Uri.Builder builder = Uri.parse(url).buildUpon(); 

    for (String name : params.keySet()) { 
     builder.appendQueryParameter(name, params.get(name).toString()); 
    } 

    url = builder.build().toString(); 
    HttpGet request = new HttpGet(url); 
    HttpResponse response = client.execute(request); 
    return EntityUtils.toString(response.getEntity(), "UTF-8"); 
0
class Searchsync extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... params) { 

     HttpClient httpClient = new DefaultHttpClient();/*write your url in Urls.SENDMOVIE_REQUEST_URL; */ 
     url = Urls.SENDMOVIE_REQUEST_URL; 

     url = url + "/id:" + m; 
     HttpGet httpGet = new HttpGet(url); 

     try { 
      // httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // httpGet.setEntity(new StringEntity(json.toString())); 
      HttpResponse response = httpClient.execute(httpGet); 
      HttpEntity resEntity = response.getEntity(); 

      if (resEntity != null) { 

       String responseStr = EntityUtils.toString(resEntity).trim(); 

       Log.d("Response from PHP server", "Response: " 
         + responseStr); 
       Intent i = new Intent(getApplicationContext(), 
         MovieFoundActivity.class); 
       i.putExtra("ifoundmovie", responseStr); 
       startActivity(i); 

      } 
     } catch (UnsupportedEncodingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return null; 
    }//enter code here 

} 
0

Nếu bạn có liên tục URL tôi khuyên bạn nên sử dụng đơn giản http-request xây dựng trên apache http.

Bạn có thể xây dựng khách hàng của bạn như sau:

private filan static HttpRequest<YourResponseType> httpRequest = 
        HttpRequestBuilder.createGet(yourUri,YourResponseType) 
        .build(); 

public void send(){ 
    ResponseHendler<YourResponseType> rh = 
     httpRequest.execute(param1, value1, param2, value2); 

    handler.ifSuccess(this::whenSuccess).otherwise(this::whenNotSuccess); 
} 

public void whenSuccess(ResponseHendler<YourResponseType> rh){ 
    rh.ifHasContent(content -> // your code); 
} 

public void whenSuccess(ResponseHendler<YourResponseType> rh){ 
    LOGGER.error("Status code: " + rh.getStatusCode() + ", Error msg: " + rh.getErrorText()); 
} 

Lưu ý: Có rất nhiều phương pháp hữu ích để thao tác trả lời của bạn.

Các vấn đề liên quan