【发布时间】:2013-11-23 07:22:30
【问题描述】:
我正在编写一个 Android 应用程序,并且一直在寻找一种从我要发布到的服务器中获取 _VIEWSTATE 的方法,以便我可以将其放入我的 Http 发布内容中。一些人推荐了正则表达式,但其他一些专业人士强烈反对使用正则表达式解析 HTML。那么,如何解析 _VIEWSTATE 呢?我在 AsyncTask 中使用 HttpURLConnection/HttpsURLConnection。另外,我不需要把 InputStream 阅读器放在首位,才能先获得 _VIEWSTATE 吗?所有的 android 示例都将输入流放在输出流之后。到目前为止,这是我的代码的样子(发布到一个必须“点击通过”的三个页面的网站):
在我的活动中,我这样调用异步任务:
//execute AsyncTask for all three reports
submit_report.execute(report1, report2, report3);
我的异步任务 doInBackground 方法:
class UploadReportTask extends AsyncTask<HashMap<String,String>, ProgressBar, Void> {
//this is called on task.execute
protected Void doInBackground(HashMap<String,String>...maps) {
System.out.println("Report is being uploaded");
URL url = null;
try {
url = new URL(getString(R.string.url_dnc));
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-Charset", utf);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + utf);
urlConnection.setChunkedStreamingMode(0);
//For each map in maps, encode the map,
//get the headers, add the headers to the map, convert to bytes,
//then post the bytes,
//get response.
for (HashMap<String,String> map : maps){
byte[] payload = makePayload(map);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//urlConn.connect //I think this happens here
out.write(payload);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int length = in.read();
String result, line = reader.readLine();
result = line;
while (length != -1){
result+=line;
}
System.out.println(result);
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
urlConnection.disconnect();
}
return null;
}
【问题讨论】:
标签: java android hashmap http-post httpurlconnection