在该行中: httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs));
我收到错误消息: The method setEntity(UrlEncodedFormEntity) is undefined for the type HttpGet
HttpClient httpclient = new DefaultHttpClient();
// Add the header data for the request
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("phonenumber","12345"));
nameValuePairs.add(new BasicNameValuePair("authtoken", "12345"));
HttpGet httpget = new HttpGet(url);
httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpget);
答案 0 :(得分:6)
GET请求没有可以包含实体的主体,您想要包含的参数应该内置在URL本身中。
干净的方法是使用URIBuilder
:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost(host).setPort(port).setPath(yourpath)
.setParameter("parts", "all")
.setParameter("action", "finish");
答案 1 :(得分:3)
尝试使用BasicNameValuePair List添加params并从URLEncodedUtils获取格式化的字符串,该字符串连接到url:
HttpClient httpclient = new DefaultHttpClient();
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("phonenumber", "12345"));
params.add(new BasicNameValuePair("authtoken", "12345"));
HttpGet httpget = new HttpGet(url+"?"+URLEncodedUtils.format(params, "utf-8"));
HttpResponse response = httpclient.execute(httpget);
答案 2 :(得分:0)
尝试这样,
我使用NameValuePair和URLEncodedUtils列表来创建我想要的url字符串。
protected String addLocationToUrl(String url){
if(!url.endsWith("?"))
url += "?";
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
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;
}
答案 3 :(得分:0)
原因是因为setEntity方法属于HttpPost。不是HttpGet,只需将HttpGet更改为HttpPost即可纠正错误。
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
也在您的php代码中将所有$_GET["your key"];
方法更改为$_POST["your key"];