【问题标题】:http request and http response in android?android中的http请求和http响应?
【发布时间】:2012-02-29 03:14:08
【问题描述】:

我正在处理:

org.apache.http.HttpResponse;
org.apache.http.client.HttpClient;
org.apache.http.client.methods.HttpGet;
org.apache.http.impl.client.DefaultHttpClient;

我正在使用jsp编写服务器端代码。

我不知道从我的模拟器向服务器发送一些值的过程。 并从服务器响应中获取一个字符串的值。

我的意思是说……要使用哪些方法?如何使用它们?

【问题讨论】:

    标签: android httpclient httprequest httpresponse httpcontext


    【解决方案1】:

    发送 HTTP GET 请求并检索响应:

    private static void get(final Context context, final String url) {
        new Thread() {
            @Override
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = Utils.createHttpRequest(context, url, true, false);
                setProxyIfNecessary(context, request);
                try {
                    HttpResponse response = client.execute(request);
                    Log.v("Test", "StatusCode: " + response.getStatusLine().getStatusCode() + ", Entity: " + EntityUtils.toString(response.getEntity()));
                } catch (Exception e) {
                    // Oh, crash
                }
            }
        }.start();
    }
    
    private static void setProxyIfNecessary(Context context, HttpUriRequest request) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivity == null ? null : connectivity.getActiveNetworkInfo();
        if (networkInfo == null || networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return;
        }
    
        String proxyHost = Proxy.getHost(context);
        if (proxyHost == null) {
            return;
        }
    
        int proxyPort = Proxy.getPort(context);
        if (proxyPort < 0) {
            return;
        }
    
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
    }
    

    调用方式:

    get(context, "http://developer.android.com/index.html");
    

    你会得到logcat *:S Test:V的日志

    注意新增线程是为了避免阻塞UI线程

    【讨论】:

      【解决方案2】:

      下面是我实现的用于将用户名和密码从 android 发送到服务器端 JSP 页面的代码。来自服务器的响应是一个json对象,然后被处理。代码如下。

      import java.util.ArrayList;
      import java.util.List;
      
      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.NameValuePair;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.entity.UrlEncodedFormEntity;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.apache.http.message.BasicNameValuePair;
      import org.apache.http.util.EntityUtils;
      import org.json.JSONException;
      import org.json.JSONObject;
      
      import android.app.Activity;
      import android.app.ProgressDialog;
      import android.content.Intent;
      import android.os.AsyncTask;
      import android.os.Bundle;
      import android.util.Log;
      import android.view.View;
      import android.widget.Button;
      import android.widget.EditText;
      import android.widget.TextView;
      
      
      public class Login_Menu extends Activity {
      
      EditText usname;
      EditText pass;
      TextView tv;
      HttpClient client;
      HttpPost post;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.login_lay);
       tv=(TextView) findViewById(R.id.login_stat_tv);
       usname=(EditText)findViewById(R.id.uname);
       pass=(EditText)findViewById(R.id.pass);
      Button login=(Button)findViewById(R.id.login_but);
      Button cancel=(Button)findViewById(R.id.cancel_but);
      
      client = new DefaultHttpClient();
      String url="http://10.0.2.2:7001/proj/login.jsp";
      post = new HttpPost(url);
      login.setOnClickListener(new View.OnClickListener() {
      
          public void onClick(View arg0) {
              new login().execute("");
          }
      });
      
      cancel.setOnClickListener(new View.OnClickListener() {
      
          public void onClick(View v) {
              usname.getText().clear();
              pass.getText().clear();
          }
      });
      
      }
      
      
      
      
      private class login extends AsyncTask<String, Void, JSONObject>{
      
      ProgressDialog dialog = ProgressDialog.show(Login_Menu.this, "", "Authenticating, Please wait...");
      
      @Override
      protected JSONObject doInBackground(String... params) {
          Log.i("thread", "Doing Something...");
         //authentication operation
      try{
      
          List<NameValuePair> pairs = new ArrayList<NameValuePair>();   
          pairs.add(new BasicNameValuePair("username",usname.getText().toString()));   
          pairs.add(new BasicNameValuePair("password",pass.getText().toString()));   
          post.setEntity(new UrlEncodedFormEntity(pairs));   
          HttpResponse response = client.execute(post);
          int status=response.getStatusLine().getStatusCode();
      
          if(status == 200)
          {
              HttpEntity e=response.getEntity();
              String data=EntityUtils.toString(e);
              JSONObject last=new JSONObject(data);
              return last;
      
          }
      
      }
      
        catch(Exception e)
      {
          e.printStackTrace();   
      
      }
      
          return null;
      }
      
      protected void onPreExecute(){
          //dialog.dismiss();
          Log.i("thread", "Started...");
          dialog.show();
      }
      protected void onPostExecute(JSONObject result){
          Log.i("thread", "Done...");
          String status;
          String name;
          try {
              status= result.getString("status");
              name=result.getString("uname");
      
             if(dialog!=null)
             {
               dialog.dismiss();
             }
             else{}
      
           if(status.equalsIgnoreCase("yes"))
                {
              tv.setText("Login Successful...");
      
              Bundle newbundle=new Bundle();
              newbundle.putString("uname",name);
      
              Intent myIntent=new Intent(Login_Menu.this,Instruction.class);
              myIntent.putExtras(newbundle);
      
              startActivity(myIntent);
      
              }
            else{
      
                  tv.setText("No User Found, please try again!");
              }
          } catch (JSONException e) {
              e.printStackTrace();
          }
         }
      
        }
      
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-25
        • 1970-01-01
        • 2011-02-23
        • 2011-11-10
        • 1970-01-01
        • 1970-01-01
        • 2021-08-28
        相关资源
        最近更新 更多