【问题标题】:Http Post Request android in a different threadHttp Post Request android在不同的线程中
【发布时间】:2014-02-18 23:50:08
【问题描述】:

我是 android 新手,我正在尝试发出 http post 请求,但我收到以下错误,我已经发布了我的代码和我的 LogCat 的一些行。我是否应该在不同的课程中执行此操作,如果是,如何执行,或者这只是我必须在当前代码中修复的问题。

public class PasteCode extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pastecode);

    final EditText codeinput = (EditText) findViewById(R.id.editText1);

    Button send_btn = (Button) findViewById(R.id.button1);
    send_btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            final String code = codeinput.getText().toString();

            new Thread( new Runnable() {
                @Override
                public void run() {

                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("accounts.google.com");

                    ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
                    nameValuePair.add(new BasicNameValuePair("code", code));
                    nameValuePair.add(new BasicNameValuePair("client_id", "----------------------"));
                    nameValuePair.add(new BasicNameValuePair("client_secret", "-----------------"));
                    nameValuePair.add(new BasicNameValuePair("redirect_uri", "urn:ietf:wg:oauth:2.0:oob"));
                    nameValuePair.add(new BasicNameValuePair("grant_type", "authorization_code"));

                    try {
                        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

                    } catch (UnsupportedEncodingException e) {
                        // writing error to Log
                        e.printStackTrace();
                    }

                    // Making HTTP Request
                    try {
                        HttpResponse response = httpClient.execute(httpPost);

                        // writing response to log
                        Log.d("Http Response:", response.toString());
                    } catch (ClientProtocolException e) {
                        // writing exception to log
                        e.printStackTrace();
                    } catch (IOException e) {
                        // writing exception to log
                        e.printStackTrace();

                    }

                }
            }).start();
        }
    });
}
}

日志视图

02-18 10:03:20.477: W/dalvikvm(3759): threadid=15: 线程未捕获而退出 异常(组=0x4001d760)

02-18 10:03:20.487:E/AndroidRuntime(3759):致命异常:Thread-31

02-18 10:03:20.487: E/AndroidRuntime(3759): java.lang.IllegalStateException: 目标 host 不能为空,也不能在参数中设置。 方案=空,主机=空, path=accounts.google.com

02-18 10:03:20.487: E/AndroidRuntime(3759): at java.lang.Thread.run(Thread.java:1020)

【问题讨论】:

    标签: android http-post


    【解决方案1】:

    早上好,请您发布 logcat 错误...实际上 android 不允许您在应用程序的主线程中发出 http 请求...有一些方法可以实现您正在寻找的东西.. . 首先你可以将你的线程实现为 asyncTask...

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    

    但不建议这样做...

    编辑:

    好的,我看到您的错误,没有数据库或没有任何东西可以处理您发送的数据...能否请您在服务器端发布您拥有的代码...并检查您发送数据的 url.. .这似乎无效...我将发布一个示例来向您展示如何使其工作..!!

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("data1", "data"));
            nameValuePairs.add(new BasicNameValuePair("data2", "dataa"));
            nameValuePairs.add(new BasicNameValuePair("data3", "dataaa"));
            try {
                res = CustomHttpClient.sendData("URL", nameValuePairs);
                String resp = res.toString();
                Log.e(Tag, res);
                resp = resp.replaceAll("\\s+","");
    

    如您所见,我正在创建一个自定义 http 客户端的实例,该客户端负责调用服务器...并且还负责处理来自服务器的应答...

    公共类 CustomHttpClient{

    public static final int HTTP_TIMEOT = 30 * 1000;
    private static HttpClient mHttpClient;
    
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) ;
        {
            mHttpClient = new DefaultHttpClient();
            final HttpParams param = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(param, HTTP_TIMEOT);
            HttpConnectionParams.setSoTimeout(param, HTTP_TIMEOT);
            ConnManagerParams.setTimeout(param, HTTP_TIMEOT);
        }
        return mHttpClient;
    }
    
    public static String sendData(String url, ArrayList nameValuePairs) throws Exception {
        BufferedReader reader = null;
        try {
            HttpClient httpclient = getHttpClient();
            HttpPost httppost = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs);
            httppost.setEntity(formEntity);
    
            HttpResponse response = httpclient.execute(httppost);
            reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sBuffer = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = reader.readLine()) != null) {
                sBuffer.append(line + NL);
            }
            reader.close();
            String result = sBuffer.toString();
            return result;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    }

    【讨论】:

    • 我通过在路径名中添加“http://”解决了这个错误,现在我正在努力阅读我得到的响应。
    • 响应应该包含我正在验证的用户的访问令牌。我在我的代码中做到了这一点 - Log.d("Http Response:", response.toString());并在 LogCat 中显示 Http Response - org.apache.http.message.BasicHttpResponse@43454f20 那么我该如何阅读消息
    • 你可以试试这个教程...blog.notdot.net/2010/05/…
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2011-09-22
    • 2022-08-09
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    相关资源
    最近更新 更多