Answers:
我使用NameValuePair和URLEncodedUtils列表创建所需的url字符串。
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;
}
要使用get参数构建uri,Uri.Builder提供了一种更有效的方法。
Uri uri = new Uri.Builder()
.scheme("http")
.authority("foo.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
从HttpComponents开始, 4.2+
有一个新类URIBuilder,它提供了生成URI的便捷方法。
您可以直接从字符串URL使用创建URI:
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();
创建URI
对象后,只需创建HttpGet
对象并执行即可:
//create GET request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.
方法
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");
或使用发布请求,如果有兴趣,请在此处说明get和post请求之间的区别
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);
注意: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");
如果您有常数,URL
我建议使用基于apache http构建的简化的http请求。
您可以按照以下方式构建客户端:
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());
}
注意:有许多有用的方法可以处理您的响应。