使用Async Task将大型String从Android发送到Servlet

时间:2015-07-02 15:04:51

标签: java android servlets android-asynctask network-programming

在我的应用中,我通过StringBasicNameValuePairs方式向Servlet发送 HttpClient httpClient = new DefaultHttpClient(); //127.0.0.1 - 10.201.19.153 HttpPost httpPost = new HttpPost(conn.urls.get("now")); List<NameValuePair> nameValuePairs = new ArrayList<>(1); nameValuePairs.add(new BasicNameValuePair("order", order));//"tours" if(order.equals("reservation")){ String booking = new Gson().toJson(reservation); nameValuePairs.add(new BasicNameValuePair("reservation", booking)); } try { // Add name data to request httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); //... } //...

String

除了使用BasicNameValuePairs之外还有另一种发送sudo rabbitmqctl add_vhost /的方式,或者这是唯一的方法吗?

1 个答案:

答案 0 :(得分:1)

我不知道为什么你需要一个替代品,但在这里它是.. 而不是使用Gson你可以使用以下代码

{
...
    List<NameValuePair> params = new ArrayList<>();
     params.add(new BasicNameValuePair("string",longString));
     makeHttpRequest(url,"POST", params);
...
}

    public void makeHttpRequest(String url, String method, List<NameValuePair> params) {


        try {
            if (method == "POST"){
                DefaultHttpClient httpClient= new DefaultHttpClient();
                HttpPost httpPost =new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse=httpClient.execute(httpPost);
                HttpEntity httpEntity=httpResponse.getEntity();
                is=httpEntity.getContent();

            }else if (method == "GET"){

                DefaultHttpClient httpClient=new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params,"utf-8");
                if (!paramString.matches(""))
                {
                url +="?"+paramString;
                }
                HttpGet httpGet = new HttpGet(url);
                lru =url;

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity=httpResponse.getEntity();
                is=httpEntity.getContent();

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

我希望它有所帮助