Build_HttpBody()// httpPost.setEntity()的问题 - Android

时间:2014-11-20 11:03:58

标签: android android-studio http-post httprequest httpclient

我使用AndroidStudio开发AndroidApps我开始做一个简单的HttpPost请求我遇到了问题,我发现的所有帖子都是这样做的:

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

但是当我尝试调试App Android Studio时,在这行中给出了2个错误:

 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

我可能需要安装更多库或支持库吗?我做得不好?有人可以帮帮我吗?提前致谢,对不起我的英语!

PD1:如果您需要更多信息或代码,请告诉我!

2 个答案:

答案 0 :(得分:1)

  

2016年更新

使用 HttpURLConnection 类,我们需要打开 BufferedWritter 以插入我们的实体值,如下代码所示:

//Declaration of variables
private List<NameValuePair> ListOfValues;
...

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

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

    //Declaration of variables
    InputStream is = null;
    String Result = "";

    URL urll = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urll.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(Build_HttpBody(ListOfValues));
    writer.flush();
    writer.close();
    os.close();

    // Starts request
    conn.connect();
    int ResponseCode = conn.getResponseCode();

    if (ResponseCode == 200) {
        is = conn.getInputStream();
        String EntityResult = ReadResponse_HttpURLConnection(is);
    } 
    else {
        throw new RuntimeException("Invalid Status Code");
    }
}

  

注意不推荐使用DefaultHttpClient类(2011)

有关此link之后的详细信息。

尝试使用以下代码,请记住这种情况始终使用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();
        }
    }
}

答案 1 :(得分:0)

您显然没有处理从构造函数抛出的IO异常:

请参阅:Android docs on UrlEncodedFormEntity

让我感到困惑的是,你的IDE没有报告这个,或者这个代码甚至是如何编译的,更不用说运行/调试了。

编辑: 如果你是这个东西的新手,也许值得一看: Android Volley,这是Google为Android网络开发的一个非常简单但有效的库。