如何将参数添加到Android中的HTTP GET请求?
我有一个HTTP GET请求,我试图发送。 我尝试通过首先创build一个BasicHttpParams
对象并将该参数添加到该对象,然后调用我的HttpGet
对象上的setParams( basicHttpParms )
来尝试向此请求添加参数。 此方法失败。 但是,如果我手动添加我的参数到我的url(即附加?param1=value1¶m2=value2
)成功。
我知道我在这里失去了一些东西,任何帮助将不胜感激。
我使用NameValuePair和URLEncodedUtils列表来创build我想要的urlstring。
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; }
通过获取参数来构builduri,Uri.Builder提供了一个更有效的方法。
Uri uri = new Uri.Builder() .scheme("http") .authority("foo.com") .path("someservlet") .appendQueryParameter("param1", foo) .appendQueryParameter("param2", bar) .build();
方法
setParams()
喜欢
httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));
只添加HttpProtocol参数。
要执行httpGet,您应该手动将您的参数附加到url
HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo¶m2=bar");
或者使用post请求get和post请求之间的区别在这里解释,如果你有兴趣的话
从HttpComponents 4.2+
有一个新的类URIBuilder ,它提供了生成URI的方便途径。
您可以使用直接从stringURL创buildURI:
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();
否则,您可以显式指定所有参数:
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();
一旦你创build了URI
对象,那么你只需要创buildHttpGet
对象并执行它:
//create GET request HttpGet httpGet = new HttpGet(uri); //perform request httpClient.execute(httpGet ...//additional parameters, handle response etc.
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
注意: url = new URI(...)
是越野车
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");
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 }