gpt4 book ai didi

java - 如何在使用 HttpURLConnection (android/java) 发布之前获取 VIEWSTATE?

转载 作者:行者123 更新时间:2023-12-01 13:48:29 24 4
gpt4 key购买 nike

我正在编写一个 Android 应用程序,并且一直在寻找一种从我想要发布到的服务器获取 _VIEWSTATE 的方法,以便我可以将其放入我的 Http 发布内容中。一些人推荐了正则表达式,但其他一些专业人士强烈反对使用正则表达式解析 HTML。那么,如何解析 _VIEWSTATE ?我在 AsyncTask 中使用 HttpURLConnection/HttpsURLConnection。另外,我不需要先放置 InputStream 读取器,然后先获取 _VIEWSTATE 吗?所有的 android 示例都将输入流放在输出流之后。这是我的代码到目前为止的样子(发布到一个具有必须“点击”的三个页面的网站):

在我的 Activity 中,我像这样调用异步任务:

//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;
}

最佳答案

protected String parseViewstate(String response){
int i = 0;
String viewstate = "";
while (true){
int found = response.indexOf("\"__VIEWSTATE\"", i);
if (found == -1) break;
int start = found + 38; //check numbers from start of "__V"
int end = (response.indexOf("/>", start)) -2;
viewstate = response.substring(start, end);
i = end + 1;
}return viewstate;
}

关于java - 如何在使用 HttpURLConnection (android/java) 发布之前获取 VIEWSTATE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20159756/

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