有httpPost.setEntity问题() - 机器人 [英] Problems with a httpPost.setEntity() - Android

查看:6508
本文介绍了有httpPost.setEntity问题() - 机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发AndroidApps与AndroidStudio我开始做一个简单的HttpPost请求和我有一个问题,所有的职位,我能找到这样做:

I develop AndroidApps with AndroidStudio I start to do a simple HttpPost Request and I had a problems, all post that I could find do this:

private void CheckLoguin_Request(String User, String Pass){

    //Declaration of variables
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost Request = new HttpPost(url_Loguin);
    HttpResponse Response;

    List<NameValuePair> BodyRequest_Elements = new ArrayList<NameValuePair>();
    BodyRequest_Elements.add(new BasicNameValuePair("user_name", User));
    BodyRequest_Elements.add(new BasicNameValuePair("user_passwd", Pass));

    Request.setEntity(new UrlEncodedFormEntity(BodyRequest_Elements));
    Response = httpClient.execute(Request);

    // writing response to log
    Log.d("Http Response:", Response.toString());
}

但是,当我尝试debugg应用程序的Andr​​oid工作室给我2个错误在这行:

But when I try to debugg App Android Studio give me a 2 errors in this lines:

 new UrlEncodedFormEntity(BodyRequest_Elements) //Error:(40, 27) error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown

 Response = httpClient.execute(Request); //Error:(41, 38) error: unreported exception IOException; must be caught or declared to be thrown

这是可能的,我需要安装更多的库或者支持库?我做的不好?任何人都可以帮助我吗?在此先感谢和抱歉,我的英语水平!

It's possible I need install more libraries or support libraries? What I do bad? Anyone can helps me? Thanks in advance and sorry for my English!

PD1:如果您需要了解更多信息或code告诉我

PD1: If you need more info or code advise me!

推荐答案

尝试使用这个下面code,记住这种情况下,始终使用AsyncTask的:

try to use this following code, remember for this case always use AsyncTask:

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

    Context cx;
    String Url;
    List<NameValuePair> BodyRequest_Elements;

    public Check_Loguin_Request(Context cx,String url, List<NameValuePair> ListOfValues)
    {
        this.cx = cx;
        this.Url = url;
        this.BodyRequest_Elements = ListOfValues;
    }

    private String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

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

        //Declaration of variables
        DefaultHttpClient httpClient;
        HttpPost Request = new HttpPost(url_Loguin);
        HttpResponse Response;
        HttpParams httpParameters = new BasicHttpParams();
        httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        httpClient = new DefaultHttpClient(httpParameters);


        try {
            HttpEntity entity = new UrlEncodedFormEntity(BodyRequest_Elements);
            Request.setHeader(entity.getContentType());
            Request.setEntity(entity);

            Response = httpClient.execute(Request);

            if(Response.getStatusLine().getStatusCode() == 200){
                String EntityResult = EntityUtils.toString(Response.getEntity());
                //HttpEntity EntityResult = Response.getEntity();
                //InputStream iStream = EntityResult.getContent();
                //JSONObject json = new JSONObject(convertStreamToString(iStream));

                EntityResult = EntityResult.replaceAll("[()]", "");
                JSONObject json = new JSONObject(EntityResult);

                String Result = json.optString("code").toString();
                return Result;
            }
            else{
                throw new RuntimeException("Invalid Status Code");
            }
        }
        catch (Exception ex){
            Log.getStackTraceString(ex);
            return ex.toString();
        }
    }
}

这篇关于有httpPost.setEntity问题() - 机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆