发送特定的 POST 请求以接收 base64 格式的文本文件并将其显示在 WebView 上



我想寻求有关 POST 请求的帮助。
我想在服务器上发送一个特定的帖子,如果我发送正确的身份验证,那么它会发回以base64格式格式化的图像,然后我想在WebView中显示它。

我有 2 个编辑文本字段和一个按钮作为布局。一个文本字段
用于登录,第二个文本字段用于密码。 登录名作为带有密钥用户名的 POST 参数在消息正文中发送。 密码使用 SHA-1 加密,并在名为授权的字段中以标头发送。使用按钮,我可以发送应如下所示的 Post 请求>

POST/download/image.php HTTP/1.1
授权:myPass
内容类型:application/x-www-form-urlencoded
主机:www.myweb.com

我的代码在这里。但它根本不起作用。我是帖子请求的新手,所以我真的没有 知道如何正确编写它。

@Override
public void onClick(View arg0) {
String login = mLoginView.getText().toString();
String pass = mPasswordView.getText().toString();
URL url = null;
try {
url = new URL("https://www.myweb.com/download/image.php");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
if (login.length() == 0) {
login = "correctpass";
}
if (pass.length() == 0) {
pass = "correctlogin";
}
//calling getter for parsing the password into SHA1 hash
try {
pass = (String) HashTool.getSHA1Hash(pass);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Key","username");
DataOutputStream outputPost = new DataOutputStream(new BufferedOutputStream(connection.getOutputStream()));
outputPost.write(login.getBytes());
writeStream(outputPost);
//this getBytes method won't work
connection.setFixedLengthStreamingMode(outputPost.getBytes().length);
outputPost.close();
connection.setDoOutput(true);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null) // Make sure the connection is not null.
connection.disconnect();
}

这是 writeStream(( 方法。我不知道如何正确地做到这一点。

//method used for post request
private void writeStream(DataOutputStream out) throws IOException {
String output = "something here??? maybe post ?";
out.write(output.getBytes());
out.flush();
}

此方法在链接上以POST形式发送数据:

private void executeLink(String link, String urlParameters) throws Exception{

String response = null;
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
URL    url            = new URL( link );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );

try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}
conn.connect();
if(conn.getResponseCode() == 200){
//some thing else
}else{
//rejected 
}
return response;
}

调用方法:

executeLink("url.link" , "param1=1&param2=val2&param2=val3")

最新更新