Android 2.3.3 中的 Http 获取请求

Posted

技术标签:

【中文标题】Android 2.3.3 中的 Http 获取请求【英文标题】:Http get request in Android 2.3.3 【发布时间】:2012-05-14 09:52:26 【问题描述】:

我在发送HTTP GET 请求方面需要帮助。我的代码如下:

    URL connectURL = new URL("url");
    HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection(); 

    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    conn.setUseCaches(false); 
    conn.setRequestMethod("GET"); 

    conn.connect();
    conn.getOutputStream().flush();      
    String response = getResponse(conn);

但它在getResponse(conn); 失败了,为什么?

【问题讨论】:

getResponse 来自哪里(这段代码放在什么类中),错误是什么? 【参考方案1】:

GET 请求可以这样使用:

try 
    HttpClient client = new DefaultHttpClient();  
    String getURL = "http://www.google.com";
    HttpGet get = new HttpGet(getURL);
    HttpResponse responseGet = client.execute(get);  
    HttpEntity resEntityGet = responseGet.getEntity();  
    if (resEntityGet != null)   
        // do something with the response
        String response = EntityUtils.toString(resEntityGet);
        Log.i("GET RESPONSE", response);
    
 catch (Exception e) 
    e.printStackTrace();

【讨论】:

我要发参数,怎么办? 您可以像这样添加参数:“google.com?param1=value1&param2=value2”还有发送数据的POST方法,这种情况下您通常不需要在url中添加参数,这是更可取的。 diffen.com/difference/Get_vs_Post【参考方案2】:

我相信 setDoOutput(true) 自动暗示 POST。

【讨论】:

【参考方案3】:

我将这段代码用于 GET 响应,这对我来说工作正常:

HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(requestUrl);

    HttpResponse response=null;
    try 
        response = client.execute(request);
     catch (ClientProtocolException e) 
        Log.d(TAG,"1. "+e.toString());

     catch (IOException e) 
        Log.d(TAG,"2. "+e.toString());

    
    int status_code=response.getStatusLine().getStatusCode();
    Log.d(TAG,"Response Code returned ="+status_code);

    BufferedReader in=null;
    try 
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
     catch (IllegalStateException e) 
        Log.d(TAG,"3. "+e.toString());
     catch (IOException e) 
        Log.d(TAG,"4. "+e.toString());
    

    StringBuffer sb = new StringBuffer("");
    String line = "";
    String newline = System.getProperty("line.separator");
    try 
        while ((line = in.readLine()) !=null)
            sb.append(line + newline);
        
        String data = sb.toString();
        Log.d(TAG,data);
     catch (IOException e) 
        Log.d(TAG,"5. "+e.toString());
    
    try 
        in.close();
     catch (IOException e) 
        Log.d(TAG,"6. "+e.toString());
    
    String data = sb.toString();

    try 
        if(status_code==200 || status_code==401)
            JSONObject responseJSONObject = new JSONObject(data);
            responseJSONObject.put("tpg_status_code", status_code);
        
     catch (JSONException e) 
        Log.d(TAG,"6. "+e.toString());
    

【讨论】:

【参考方案4】:

我使用此代码,它运行良好:

public class HttpGetandroidExample extends Activity 

            TextView content;
            EditText fname,email,login,pass;

        @Override
        protected void onCreate(Bundle savedInstanceState) 

                  super.onCreate(savedInstanceState);
                 setContentView(R.layout.activity_http_get_android_example);

                 content   =  (TextView)findViewById(R.id.content);
                 fname     =  (EditText)findViewById(R.id.name);
                 email      =  (EditText)findViewById(R.id.email);
                 login       =  (EditText)findViewById(R.id.loginname);
                 pass       =  (EditText)findViewById(R.id.password);

               Button saveme=(Button)findViewById(R.id.save);


        saveme.setOnClickListener(new Button.OnClickListener()
          public void onClick(View v)
            
                      //ALERT MESSAGE
                     Toast.makeText(getBaseContext(),"Please wait, connecting to server.",Toast.LENGTH_LONG).show();

            try 

                 // URLEncode user defined data

                   String loginValue    = URLEncoder.encode(login.getText().toString(), "UTF-8");
                   String fnameValue  = URLEncoder.encode(fname.getText().toString(), "UTF-8");
                   String emailValue   = URLEncoder.encode(email.getText().toString(), "UTF-8");
                   String passValue    = URLEncoder.encode(pass.getText().toString(), "UTF-8");

                // Create http cliient object to send request to server

                   HttpClient Client = new DefaultHttpClient();

                // Create URL string

                 String URL = "http://androidexample.com/media/webservice/httpget.php?user="+loginValue+"&name="+fnameValue+"&email="+emailValue+"&pass="+passValue;

                //Log.i("httpget", URL);

               try
                
                              String SetServerString = "";

                            // Create Request to server and get response

                              HttpGet httpget = new HttpGet(URL);
                             ResponseHandler<String> responseHandler = new BasicResponseHandler();
                             SetServerString = Client.execute(httpget, responseHandler);

                              // Show response on activity 

                             content.setText(SetServerString);
                 
               catch(Exception ex)
                  
                         content.setText("Fail!");
                   
            
          catch(UnsupportedEncodingException ex)
           
                   content.setText("Fail");
                 
        
    );  

【讨论】:

以上是关于Android 2.3.3 中的 Http 获取请求的主要内容,如果未能解决你的问题,请参考以下文章

我的Android进阶之旅解决Android Studio的Translate插件报错 TKK:更新TTK失败,请检查网络连接问题

我的Android进阶之旅解决Android Studio的Translate插件报错 TKK:更新TTK失败,请检查网络连接问题

在 Android Studio 2.3.3 中查找组件树

Android_WebServices_源代码分析

Android 手机卫士--自定义控件(获取焦点的TextView)

在android中的视图中插入视图