如何在Android中执行URL?

时间:2015-04-05 14:32:51

标签: java android

我的活动包含EditTextButton。现在,当按下按钮时,EditText中的文本应转换为String并放入要执行的URL中。

我的链接:" http://necrecords.16mb.com/complaints.php?username=" + String;

当我在浏览器中运行上述链接时,我的数据库已成功更新。但是当我在我的Activity中使用它时(按下按钮时),应用程序崩溃了。我在Manifest中添加了Internet权限,但仍然没有结果。在成功执行上述链接后,它什么都不返回。我只是希望链接被执行,我不想要链接的任何结果。

ReportActivity.java

package com.example.telugump3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class ReportActivity extends Activity{

    EditText et;
    String mname;
    HttpPost httppost;
       StringBuffer buffer;
       HttpResponse response;
       HttpClient httpclient;
       ProgressDialog pd;
       CustomAdapter adapter;
       ListView listProduct;
       ArrayList<String> records;
       Button btn;
       String query;
       String name;
        String id;
        BufferedReader in;
        String result=null;
        String line=null;
        int code;
        String mylink;
        HttpClient httpClient;
        HttpPost httpPost;
        List<NameValuePair> nameValuePair;


    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.report_activity);
        et = (EditText)findViewById(R.id.myedit);
        btn =(Button)findViewById(R.id.mybutton);
        mname = et.getText().toString();
        // show response on the EditText etResponse 

        try {
            query = URLEncoder.encode(mname, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        mylink = "http://necrecords.16mb.com/complaints.php?username="+query;





btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v){

            GET(mylink);    

            }

        });

    }

    public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {

            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

    // convert inputstream to String
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    // check network connection
    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) 
                return true;
            else
                return false;   
    }

}

logcat的

    04-05 20:12:33.948: I/ActivityManager(561): START u0 {cmp=com.example.telugump3/.ReportActivity} from pid 8737
04-05 20:12:34.128: I/ActivityManager(561): Displayed com.example.telugump3/.ReportActivity: +153ms
04-05 20:12:38.448: E/AndroidRuntime(8737): Process: com.example.telugump3, PID: 8737
04-05 20:12:38.448: E/AndroidRuntime(8737):     at com.example.telugump3.ReportActivity.GET(ReportActivity.java:111)
04-05 20:12:38.448: E/AndroidRuntime(8737):     at com.example.telugump3.ReportActivity$1.onClick(ReportActivity.java:82)
04-05 20:12:38.458: W/ActivityManager(561):   Force finishing activity com.example.telugump3/.ReportActivity
04-05 20:12:38.968: W/ActivityManager(561): Activity pause timeout for ActivityRecord{21d2c7c8 u0 com.example.telugump3/.ReportActivity id=0 t227 f}
04-05 20:12:40.068: W/InputDispatcher(561): channel '22878c88 com.example.telugump3/com.example.telugump3.MainActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x9
04-05 20:12:40.068: E/InputDispatcher(561): channel '22878c88 com.example.telugump3/com.example.telugump3.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
04-05 20:12:40.068: W/InputDispatcher(561): Attempted to unregister already unregistered input channel '22878c88 com.example.telugump3/com.example.telugump3.MainActivity (server)'
04-05 20:12:40.068: I/WindowState(561): WIN DEATH: Window{222ac998 u0 id=0 com.example.telugump3/com.example.telugump3.ReportActivity}
04-05 20:12:40.068: I/ActivityManager(561): Process com.example.telugump3 (pid 8737) has died.
04-05 20:12:40.068: I/WindowState(561): WIN DEATH: Window{22878c88 u0 id=0 com.example.telugump3/com.example.telugump3.MainActivity}
04-05 20:12:40.088: D/dalvikvm(8817): Process 8817 nice name: com.example.telugump3
04-05 20:12:40.088: I/ActivityManager(561): Start proc com.example.telugump3 for activity com.example.telugump3/.MainActivity: pid=8817 uid=10255 gids={50255, 3003, 1028, 1015}
04-05 20:12:40.348: I/ActivityManager(561): Displayed com.example.telugump3/.MainActivity: +277ms

1 个答案:

答案 0 :(得分:2)

您需要修改btn OnClick并在AsyncTask类中执行链接。请尝试以下方法。如果遗漏了什么,请告诉我。

 protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.report_activity);
            et = (EditText)findViewById(R.id.myedit);
            btn =(Button)findViewById(R.id.mybutton);

    btn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v){
               mname = et.getText().toString();
            // show response on the EditText etResponse 

            try {
                query = URLEncoder.encode(mname, "utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            mylink = "http://necrecords.16mb.com/complaints.php?username="+query;

             HttpAsyncTask hat = new HttpAsyncTask();
             hat.execute(mylink);


                }

            });

        }        


    private class HttpAsyncTask extends AsyncTask<String, Void, String> {

                    @Override
                    protected String doInBackground(String... urls) {

                        return httpRequestResponse(urls[0]);
                    }
                    // onPostExecute displays the results of the AsyncTask.
                    @Override
                    protected void onPostExecute(String result) {

                    }
                }

            //For HttpAsync Functions: sending requests and receiving responses
                public static String httpRequestResponse(String url){
                    InputStream inputStream = null;
                    String result = "";
                    try {
                        // create HttpClient
                        HttpClient httpclient = new DefaultHttpClient();

                        // make GET request to the given URL
                        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

                        // receive response as inputStream
                        inputStream = httpResponse.getEntity().getContent();

                        // convert InputStream to string
                        if(inputStream != null)
                            result = convertInputStreamToString(inputStream);
                        else
                            result = "InputStream did not work";

                    } catch (Exception e) {
                        Log.d("InputStream", e.getLocalizedMessage());
                    }

                    return result;
                }

        private static String convertInputStreamToString(InputStream inputStream) throws IOException{
                BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
                String line = "";
                String result = "";
                while((line = bufferedReader.readLine()) != null)
                    result += line;

                inputStream.close();
                return result;
            }