ndroid的HttpURLConnection类发送POST而

ndroid的HttpURLConnection类发送POST而

本文介绍了Android的HttpURLConnection类发送POST而params get请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我的Andr​​oid应用程序发送 HttpURLConnection类一点帮助。到现在我是用一个基本的 HTTP客户端做这个。但问题是,当我从服务器上我的应用程序崩溃与内存不足例外收到一个大的数据流。这就是为什么我做了一个研究,发现, HttpURLConnection类让我获得流成片。因此,任何人可以帮助我一点点与送我PARAMS并获得来自服务器的响应?

这是我用的是previous code是这样的:

  =的HttpClient新D​​efaultHttpClient();
                httppost =新HttpPost(http://www.rpc.your_nightmare.com);                TelephonyManager TM =(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                字符串的DeviceID = tm.getDeviceId();
                字符串分辨率= Integer.toString(getWindow()。getWindowManager()。getDefaultDisplay()的getWidth())+X+
                                             Integer.toString(getWindow()getWindowManager()getDefaultDisplay()的getHeight()。);
                字符串版本=Android的+ Build.VERSION.RELEASE;
                。string地区= getResources()getConfiguration()locale.toString();
                字符串clientApiVersion = NULL;                软件包管理系统下午= this.getPackageManager();
                PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(),0);
                clientApiVersion = packageInfo.versionName;                散列= getAuthHash();                字符串timestampSQL =SELECT DBTIMESTAMP来自用户的;
                光标光标= systemDbHelper.executeSQLQuery(timestampSQL);
                如果(cursor.getCount()== 0){
                    Log.i(光标,时间戳光标空!);
                }否则如果(cursor.getCount()大于0){
                    cursor.moveToFirst();
                    的timeStamp = cursor.getString(cursor.getColumnIndex(DBTIMESTAMP));
                }                TelephonyManager TMGR =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
                phoneNumber的= tMgr.getLine1Number();
                Log.i(手机,电话号码+ phoneNumber的);                postParameters =新的ArrayList<&的NameValuePair GT;();
                postParameters.add(新BasicNameValuePair(debug_data,1));
                postParameters.add(新BasicNameValuePair(client_auth_hash,散列));
                postParameters.add(新BasicNameValuePair(时间戳时间戳));
                postParameters.add(新BasicNameValuePair(MOBILE_PHONE,phoneNumber的));
                postParameters.add(新BasicNameValuePair(deactivate_collections,Integer.toString(索引)));
                postParameters.add(新BasicNameValuePair(client_api_ver,clientApiVersion));
                postParameters.add(新BasicNameValuePair(set_locale区域));
                postParameters.add(新BasicNameValuePair(device_os_type,版本));
                postParameters.add(新BasicNameValuePair(device_sync_type,14));
                postParameters.add(新BasicNameValuePair(device_identification_string,版本));
                postParameters.add(新BasicNameValuePair(device_identificator,DEVICEID));
                postParameters.add(新BasicNameValuePair(device_resolution)号决议);                httppost.setEntity(新UrlEn codedFormEntity(postParameters));                HTT presponse响应= httpclient.execute(httppost);
                Log.w(响应,状态行:+ response.getStatusLine()的toString());                HttpEntity实体= response.getEntity();
                InputStream的流2 = entity.getContent();
                INT NREAD;
                字节[]数据=新的字节[8 * 1024];                而((NREAD = stream2.read(数据,0,data.length))!= - 1){
                  buffer.write(数据,0,NREAD);
                }                buffer.flush();
                返回buffer.toByteArray();

和比处理这样的:

 的InputStream流=新ByteArrayInputStream的(缓冲,0,temp.length);
Log.i(温度,温度+ temp.length);
Log.i(指数,索引:+指数);
responseBody = convertStreamToString(流);
Log.i(responseBody,responseBody:+ responseBody);
//计算


解决方案

下面是可以使用的方式 HttpURLConnecion 来建立到Web服务器的连接:

  System.setProperty(http.keepAlive,假);
        连接=(HttpURLConnection类)新的URL(网址).openConnection();
        connection.setDoOutput(真);
        connection.setConnectTimeout(5000); //毫秒
        connection.setRequestMethod(POST);
        connection.setRequestProperty(连接,保持活动);
        connection.setRequestProperty(字符集,字符集);
        connection.setRequestProperty(内容类型,
                应用程序/ x-WWW的形式urlen codeD;字符集=+字符集);
        OutputStream的输出= NULL;
        尝试{
            输出= connection.getOutputStream();
            output.write(query.getBytes(字符集));
        }赶上(IOException异常五){
            e.printStackTrace();
        } {最后
            如果(输出!= NULL)
                尝试{
                    output.close();
                }赶上(IOException异常五){
                    e.printStackTrace();
                }
        }        INT状态=((HttpURLConnection类)连接).getResponse code();
        Log.d(,状态:+状态);        对于(进入<字符串列表<串GT;>标题:连接
                .getHeaderFields()。的entrySet()){
            Log.d(头
                    标题:+ header.getKey()+=
                            + header.getValue());
        }        InputStream的响应=新的BufferedInputStream(
                connection.getInputStream());        INT读取动作= -1;
        字节[]缓冲区=新的字节[30 * 1024];
        而((读取动作= response.read(缓冲液))大于0&放大器;&放大器; stopThread){
            字节[] =缓冲器2新的字节[读取动作]
            System.arraycopy(缓冲液,0,缓冲器2,0,读取动作);
            //缓冲器2是你分块响应
        }
        connection.disconnect();
    }赶上(FileNotFoundException异常五){
        e.printStackTrace();    }赶上(IOException异常五){
        e.printStackTrace();
    }

I need a little help with sending an HttpUrlConnection from my android application. Till now I was doing this with a basic Http Client. But the problem is that when I receive a big stream from the server my applications crash with outofmemory exception. And that's why I made a research and find out that HttpUrlConnection lets me to get the stream into a pieces. So can anybody help me a little bit with sending my params and getting the response from server?

The previous code that I was using is this :

                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://www.rpc.your_nightmare.com");

                TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                String deviceId = tm.getDeviceId();
                String resolution = Integer.toString(getWindow().getWindowManager().getDefaultDisplay().getWidth())+ "x" +
                                             Integer.toString(getWindow().getWindowManager().getDefaultDisplay().getHeight());
                String version = "Android " + Build.VERSION.RELEASE;
                String locale = getResources().getConfiguration().locale.toString();
                String clientApiVersion = null;

                PackageManager pm = this.getPackageManager();
                PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(), 0);
                clientApiVersion = packageInfo.versionName;

                hash = getAuthHash();

                String timestampSQL = "SELECT dbTimestamp FROM users";
                Cursor cursor = systemDbHelper.executeSQLQuery(timestampSQL);
                if(cursor.getCount()==0){
                    Log.i("Cursor","TimeStamp Cursor Empty!");
                } else if(cursor.getCount()>0){
                    cursor.moveToFirst();
                    timeStamp = cursor.getString(cursor.getColumnIndex("dbTimestamp"));
                }

                TelephonyManager tMgr =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
                phoneNumber = tMgr.getLine1Number();
                Log.i("Phone","Phone Number : "+phoneNumber);

                postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("debug_data","1"));
                postParameters.add(new BasicNameValuePair("client_auth_hash", hash));
                postParameters.add(new BasicNameValuePair("timestamp", timeStamp));
                postParameters.add(new BasicNameValuePair("mobile_phone", phoneNumber));
                postParameters.add(new BasicNameValuePair("deactivate_collections",Integer.toString(index)));
                postParameters.add(new BasicNameValuePair("client_api_ver", clientApiVersion));
                postParameters.add(new BasicNameValuePair("set_locale", locale));
                postParameters.add(new BasicNameValuePair("device_os_type", version));
                postParameters.add(new BasicNameValuePair("device_sync_type", "14"));
                postParameters.add(new BasicNameValuePair("device_identification_string", version));
                postParameters.add(new BasicNameValuePair("device_identificator", deviceId));
                postParameters.add(new BasicNameValuePair("device_resolution", resolution));

                httppost.setEntity(new UrlEncodedFormEntity(postParameters));

                HttpResponse response = httpclient.execute(httppost);
                Log.w("Response ","Status line : "+ response.getStatusLine().toString());

                HttpEntity entity = response.getEntity();
                InputStream stream2 = entity.getContent();


                int nRead;
                byte[] data = new byte[8*1024];

                while ((nRead = stream2.read(data, 0, data.length)) != -1) {
                  buffer.write(data, 0, nRead);
                }

                buffer.flush();
                return buffer.toByteArray();

and than processing it like this :

InputStream stream = new ByteArrayInputStream(buffer, 0, temp.length);
Log.i("Temp","Temp : "+temp.length);
Log.i("index","index : "+index);
responseBody = convertStreamToString(stream);
Log.i("responseBody","responseBody : "+responseBody);
//calculations
解决方案

Here is the way you can use HttpURLConnecion to make a connection to a web server :

        System.setProperty("http.keepAlive", "false");
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setConnectTimeout(5000); // miliseconds
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Charset", charset);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(query.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        int status = ((HttpURLConnection) connection).getResponseCode();
        Log.d("", "Status : " + status);

        for (Entry<String, List<String>> header : connection
                .getHeaderFields().entrySet()) {
            Log.d("Headers",
                    "Headers : " + header.getKey() + "="
                            + header.getValue());
        }

        InputStream response = new BufferedInputStream(
                connection.getInputStream());

        int bytesRead = -1;
        byte[] buffer = new byte[30 * 1024];
        while ((bytesRead = response.read(buffer)) > 0 && stopThread) {
            byte[] buffer2 = new byte[bytesRead];
            System.arraycopy(buffer, 0, buffer2, 0, bytesRead);
            // buffer2 is you chunked response
        }
        connection.disconnect();
    } catch (FileNotFoundException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }

这篇关于Android的HttpURLConnection类发送POST而params get请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:57