Http Post在另一个线程中请求android

时间:2014-02-18 15:32:46

标签: android http-post

我是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:Target                         host不能为null,或者在参数中设置。                         scheme = null,host = null,                         路径= accounts.google.com

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

1 个答案:

答案 0 :(得分:-1)

早上好,请你发布logcat错误请...实际上android不允许你在应用程序的主线程中发出http请求...有一些方法可以实现你正在寻找的东西..首先你可以将你的线程实现为asyncTask ......或者只是为了开发目的,你可以删除你可以在活动的onCreate中将这些行添加到你的代码中的多元素......

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

但不建议这样做......

编辑:

好的,我看到你的错误,没有数据库或没有任何东西可以处理你发送的数据...请你在服务器端发布你的代码...并检查你发送数据的网址..它似乎没有效果......我将发布一个例子来告诉你如何让它工作.. !!

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();
            }
        }
    }
}

}