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

Build_HttpBody()//httpPost.setEntity()-Android的问题,android,android-studio,http-post,httprequest,httpclient,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 Http

我用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());
}
我可能需要安装更多库或支持库?我做了什么坏事?有人能帮我吗?提前谢谢,对不起我的英语


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

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

见:

让我困惑的是,您的IDE并没有报告这一点,或者这段代码是如何编译的,更不用说运行/调试了

编辑: 如果你是这方面的新手,也许值得一看: ,这是一个非常简单但有效的库,由谷歌为Android网络开发

2016年更新

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

//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");
    }
}
//变量声明
私有值列表;
...
公共检查日志请求(上下文cx、字符串url、值列表)
{
这个.cx=cx;
this.Url=Url;
ListOfValues=ListOfValues;
}
@凌驾
受保护的字符串背景(字符串…字符串){
//变量声明
InputStream=null;
字符串结果=”;
URL urll=新的URL(URL);
HttpURLConnection conn=(HttpURLConnection)urll.openConnection();
连接设置读取超时(10000);
连接设置连接超时(15000);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
OutputStream os=conn.getOutputStream();
BufferedWriter writer=新的BufferedWriter(新的OutputStreamWriter(os,“UTF-8”));
write(Build_HttpBody(ListOfValues));
writer.flush();
writer.close();
os.close();
//开始请求
连接();
int ResponseCode=conn.getResponseCode();
如果(响应代码==200){
is=conn.getInputStream();
字符串EntityResult=ReadResponse\u HttpURLConnection(is);
} 
否则{
抛出新的运行时异常(“无效状态代码”);
}
}

注意DefaultHttpClient类已被弃用(2011年)

更多信息,请点击这里

请尝试使用以下代码,记住在这种情况下始终使用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();
        }
    }
}
private class Check\u Loguin\u请求扩展异步任务{
语境;
字符串Url;
列出所有元素;
公共检查日志请求(上下文cx、字符串url、值列表)
{
这个.cx=cx;
this.Url=Url;
this.BodyRequest_Elements=ListOfValues;
}
私有字符串convertStreamToString(InputStream为){
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
@凌驾
受保护的字符串背景(字符串…字符串){
//变量声明
默认httpClient httpClient;
HttpPost请求=新的HttpPost(url_Loguin);
HttpResponse响应;
HttpParams httpParameters=新的BasicHttpParams();
setParameters(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
//以毫秒为单位设置超时,直到建立连接。
//默认值为零,表示不使用超时。
int timeoutConnection=3000;
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
//设置默认套接字超时(SO\U超时)
//以毫秒为单位,这是等待数据的超时。
int timeoutSocket=5000;
HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
httpClient=新的默认httpClient(httpParameters);
试一试{
HttpEntity=新的UrlEncodedFormEntity(BodyRequest\u元素);
setHeader(entity.getContentType());
请求。设置实体(实体);
Response=httpClient.execute(请求);
if(Response.getStatusLine().getStatusCode()==200){
字符串EntityResult=EntityUtils.toString(Response.getEntity());
//HttpEntity EntityResult=Response.getEntity();
//InputStream iStream=EntityResult.getContent();
//JSONObject json=新的JSONObject(convertStreamToString(iStream));
EntityResult=EntityResult.replaceAll(“[()]”,“”);
JSONObject json=新的JSONObject(EntityResult);
字符串结果=json.optString(“代码”).toString();
返回结果;
}
否则{
抛出新的运行时异常(“无效状态代码”);
}
}
捕获(例外情况除外){
Log.getStackTraceString(ex);
返回例如toString();
}
}
}

请尝试此操作,HttpEntity entity=new UrlEncodedFormEntity(BodyRequest\u元素);setHeader(entity.getContentType());请求。设置实体(实体);显示您的基本SDK版本,虽然您的代码中没有错误,但我自己也尝试过。RegardsHow我可以向您展示我的SDK版本吗?这是我第一次使用android studio!:D问候!
 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();
        }
    }
}