解析传入的http post请求java android

时间:2012-08-08 12:00:31

标签: android parsing http-request

我正在使用Android网络服务器。当我在模拟器浏览器上访问localhost:8080时,它会提供带有密码字段的页面/表单。在成功验证密码后,我想将用户重定向到成功/失败页面。什么是读取传入的http post请求并解析密码字段以进行验证的最佳方法?正确方向的任何指针都是非常感激。我有一个提交表单的URL的处理程序。处理程序的代码是:

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;

import android.content.Context;

public class LoginHandler implements HttpRequestHandler {
private Context context = null;
public LoginHandler(Context context) {
    this.context = context;
}

@Override
public void handle(final HttpRequest request, HttpResponse response,
        HttpContext httpcontext) throws HttpException, IOException {
       HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            String resp = null;
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            if(validatePassword()==true){
             resp ="<html><head></head><body><h1>Home<h1><p>Success.</p></body></html>";
            }
            else{resp="<html><head></head><body><h1>Home<h1><p>Login Failed.</p></body></html>";}
            writer.write(resp);
            writer.flush();
        }


    });
    response.setHeader("Content-Type", "text/html");
    response.setEntity(entity);

}
boolean validatePassword(){
boolean pass=false;
//parse request body here and check for the password if true return true/else false
 return pass;
 }


 }

2 个答案:

答案 0 :(得分:5)

环顾四周后,我找到了解决方案。在handle方法中添加以下内容可以解决问题。感谢原始海报 。http://www.androiddevblog.net/android/a-bare-minimum-web-server-for-android-platform

        if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
Log.v("RequestBody", EntityUtils.toString(entity, "UTF-8"));
entity.consumeContent();
}
}

答案 1 :(得分:2)

如果这不是你要求的,我道歉,所以如果不是,请告诉我。

您可以使用JSONObject返回该密码是否已经过验证。

例如,如果密码正确,您可以将HTTP结果存储为:

{"status":200,"confirmed":"true"} 

否则为“假”。

当您从HTTP Post Request返回时,您可以将此结果存储为String,然后从中生成JSONObject。例如:

// Send the URL to a postRequest function and return the result as a String
String output = makePostRequest(url);

// Parse the String as a JSONObject and receive whether or not the login was confirmed
JSONObject o = new JSONObject(output);
String confirmed = o.getString("confirmed");
if (confirmed.equals("true")) {
    // Password confirmed - redirect user to success page
} else {
    // Password incorrect - redirect user to failure page
}

注意:如果您需要了解如何从帖子请求中接收响应代码,请参阅以下示例代码:

String output = {};

// Use bufferedreader and stringbuilder to build an output string (where conn is your HTTPUrlConnection object you used to make the post request    
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;

// Loop through response to build JSON String
while((line = br.readLine()) != null) {
    sb.append(line + "\n");
}

// Set output from response
output = sb.toString();

现在output是你可以变成JSONObject的字符串。

这有什么帮助?


修改
好的,所以您将获得的字符串格式为{"password":"somepassword"}。要解析这个,试试这个:

String s = /* the string in the format {"password":"somepassword"} */
JSONObject o = new JSONObject(s);
String password = o.getString("password");
if (password.equals(random_password_at_beginning_of_webservice) {
    // Password confirmed - redirect user to success page
} else {
    // Password incorrect - redirect user to failure page
}