gpt4 book ai didi

android - 通过 HTTP 访问 Web 服务时未获得所需的输出

转载 作者:行者123 更新时间:2023-11-29 02:13:11 25 4
gpt4 key购买 nike

我正在尝试使用 Web 服务将摄氏度转换为华氏度,但未获得所需的输出。谁能帮帮我……这是我的代码。

        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());
}
}

最佳答案

首先,HttpParams 不是查询/GET 参数的集合。正如文档所说,它用于“HTTP 协议(protocol)和框架参数”。因此,在 GET 请求的情况下,您可以通过将“?Celsius=32”附加到该 URL 或使用 Uri.Builder 来添加查询参数。对于 POST 请求,您必须使用 setEntity 方法。就像这个例子( 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);

其次,为了将响应读取为 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();
}

关于android - 通过 HTTP 访问 Web 服务时未获得所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6040205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com