[英]Not getting the required output in accessing web service by HTTP
I am trying to convert use a web service to convert celcius to farenheit and not getting the required output. 我正在尝试使用Web服务将celcius转换为farenheit,而没有获得所需的输出。 can anyone help me out...here is my code.
谁能帮我...这是我的代码。
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
httpClient.getParams().setParameter("Celsius", "32");
HttpPost httpGet = new HttpPost("http://www.w3schools.com/webservices/tempconvert.asmx");
HttpResponse response = httpClient.execute(httpGet, localContext);
tv.setText(response.toString());
}
catch (Exception e) {
tv.setText(e.toString());
}
}
} }
First of all, HttpParams
is not a collection of query/GET params. 首先,
HttpParams
不是查询/ GET参数的集合。 It's used for "HTTP protocol and framework parameters" as the docs put it. 如文档所述,它用于“ HTTP协议和框架参数”。 So, in case of a GET request, you add query params by either appending "?Celsius=32" to that URL or use the
Uri.Builder
. 因此,在GET请求的情况下,可以通过在该URL后面附加“?Celsius = 32”或使用
Uri.Builder
来添加查询参数。 For POST request, you have to use the setEntity
method. 对于POST请求,必须使用
setEntity
方法。 Like in this example ( source ): 像这个例子( source )一样:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
// add POST params
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("foo", "123"));
nameValuePairs.add(new BasicNameValuePair("bar", "456"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Secondly, in order to read the response as a String
you need something like this: 其次,为了将响应读取为
String
您需要这样的内容:
HttpResponse response = httpClient.execute(request);
InputStream content = response.getEntity().getContent();
String json = convertStreamToString(content);
// ...
private String convertStreamToString(InputStream input) throws IOException {
Reader inputReader = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(inputReader, 8192);
StringBuilder string = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
string.append(line + "\n");
}
} finally {
input.close();
}
return string.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.