I have a HTTP GET request that I am attempting to send. I tried adding the parameters to this request by first creating a BasicHttpParams
object and adding the parameters to that object, then calling setParams( basicHttpParms )
on my HttpGet
object. This method fails. But if I manually add my parameters to my URL (i.e. append ?param1=value1¶m2=value2
) it succeeds.
我正在尝试发送一个HTTP GET请求。我尝试向这个请求添加参数,首先创建一个BasicHttpParams对象,然后向该对象添加参数,然后在我的HttpGet对象上调用setParams(basicHttpParms)。这个方法失败。但是如果我手工将参数添加到我的URL(例如,追加?param1=value1¶m2=value2),它就成功了。
I know I'm missing something here and any help would be greatly appreciated.
我知道我在这里漏掉了一些东西,任何帮助都将非常感谢。
8 个解决方案
#1
224
I use a List of NameValuePair and URLEncodedUtils to create the url string I want.
我使用NameValuePair和urlencodeduty的列表来创建我想要的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;
}
#2
93
To build uri with get parameters, Uri.Builder provides a more effective way.
要使用get参数uri构建uri,请使用uri。Builder提供了一种更有效的方法。
Uri uri = new Uri.Builder()
.scheme("http")
.authority("foo.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
#3
30
As of HttpComponents 4.2+
there is a new class URIBuilder, which provides convenient way for generating URIs.
对于httpcomponent 4.2+,有一个新的类URIBuilder,它为生成uri提供了方便的方法。
You can use either create URI directly from String URL:
您可以直接使用字符串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();
Otherwise, you can specify all parameters explicitly:
否则,您可以显式地指定所有参数:
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();
Once you have created URI
object, then you just simply need to create HttpGet
object and perform it:
创建了URI对象之后,只需创建HttpGet对象并执行它:
//create GET request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.
#4
27
The method
该方法
setParams()
like
就像
httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));
only adds HttpProtocol parameters.
只会增加HttpProtocol参数。
To execute the httpGet you should append your parameters to the url manually
要执行httpGet,您应该手动将参数附加到url
HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo¶m2=bar");
or use the post request the difference between get and post requests are explained here, if you are interested
或者使用post请求get和post请求之间的区别在这里解释,如果你感兴趣的话
#5
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
Note: url = new URI(...)
is buggy
注意:url =新URI(…)有错误
#6
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");
#7
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
}
#8
0
If you have constant URL
I recommend use simplified http-request built on apache http.
如果您有常量URL,我建议使用构建在apache http上的简化http请求。
You can build your client as following:
你可以建立你的客户如下:
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());
}
Note: There are many useful methods to manipulate your response.
注意:有许多有用的方法可以操作您的响应。
#1
224
I use a List of NameValuePair and URLEncodedUtils to create the url string I want.
我使用NameValuePair和urlencodeduty的列表来创建我想要的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;
}
#2
93
To build uri with get parameters, Uri.Builder provides a more effective way.
要使用get参数uri构建uri,请使用uri。Builder提供了一种更有效的方法。
Uri uri = new Uri.Builder()
.scheme("http")
.authority("foo.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
#3
30
As of HttpComponents 4.2+
there is a new class URIBuilder, which provides convenient way for generating URIs.
对于httpcomponent 4.2+,有一个新的类URIBuilder,它为生成uri提供了方便的方法。
You can use either create URI directly from String URL:
您可以直接使用字符串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();
Otherwise, you can specify all parameters explicitly:
否则,您可以显式地指定所有参数:
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();
Once you have created URI
object, then you just simply need to create HttpGet
object and perform it:
创建了URI对象之后,只需创建HttpGet对象并执行它:
//create GET request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.
#4
27
The method
该方法
setParams()
like
就像
httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));
only adds HttpProtocol parameters.
只会增加HttpProtocol参数。
To execute the httpGet you should append your parameters to the url manually
要执行httpGet,您应该手动将参数附加到url
HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo¶m2=bar");
or use the post request the difference between get and post requests are explained here, if you are interested
或者使用post请求get和post请求之间的区别在这里解释,如果你感兴趣的话
#5
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
Note: url = new URI(...)
is buggy
注意:url =新URI(…)有错误
#6
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");
#7
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
}
#8
0
If you have constant URL
I recommend use simplified http-request built on apache http.
如果您有常量URL,我建议使用构建在apache http上的简化http请求。
You can build your client as following:
你可以建立你的客户如下:
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());
}
Note: There are many useful methods to manipulate your response.
注意:有许多有用的方法可以操作您的响应。