我想处理html表单。这个html表单在网站上,这个网站没有API。所以在这个网站上是html表单,我知道这个表单的动作和方法。我想在Android应用程序上填写此表单并获得结果。我应该做什么?
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("URL");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("FIELD1", "abc"));
nameValuePairs.add(new BasicNameValuePair("FIELD2", "abc"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是我对服务器的要求。我如何得到这个请求的结果?
答案 0 :(得分:0)
我没有非常详细的HttpClient经验,因为在我过去的经历中,我主要使用Jsoup Java库。但我也尝试过使用HttpClient,这里有一个代码片段来获取响应的内容。
可能存在与Android API相关的一些差异,但我希望它有所帮助。 (例如,CloseableHttpResponse和HttpResponse)
public static String readHttpResponse(CloseableHttpResponse response) throws IOException {
final StringBuilder builder = new StringBuilder();
try {
HttpEntity entity = response.getEntity();
if (null != entity) {
InputStream inputStream = entity.getContent();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
} finally {
inputStream.close();
}
}
} finally {
response.close();
}
return builder.toString();
} // end of readHttpResponse(CloseableHttpResponse response)
这是一个使用EntityUtils
的不同实现public static String readHttpResponse(CloseableHttpResponse response) throws IOException {
try {
HttpEntity entity = response.getEntity();
if (null != entity) {
return EntityUtils.toString(entity);
}
} finally {
response.close();
}
return "";
} // end of readHttpResponse(CloseableHttpResponse response)
如果您对使用库感兴趣,可以使用下面的代码获得相同的结果。
Connection.Response res = Jsoup.connect("URL")
.data("FIELD1", "abc", "FIELD2", "abc")
.method(Connection.Method.POST)
.execute();
String result = res.body();