如何在宁静的Web服务中发送和解码字符串?

时间:2014-09-29 07:48:15

标签: android json web-services rest restful-url

您好我正在从申请到odesk进行沟通。我收到了消息并显示在我的应用程序中,但如果我发送的是space,那就是地方%20。这是我的代码

reply = (EditText)findViewById(R.id.reply);

在这里,我将从我的edittext中获取文本并转换为字符串。

class ODESksendReplyTask extends AsyncTask<Void, Void, String>
    {
        public ProgressDialog _dialog;

        @Override
        protected void onPreExecute() 
        {
            _dialog = new ProgressDialog(context);
            _dialog.setMessage("Sending Reply...");
            _dialog.setIndeterminate(true);
            _dialog.setCancelable(false);
            _dialog.show();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params)
        {
            client.setTokenWithSecret(token,tokenSecret);

            Mc mc = new Mc(client);
            HashMap<String, String> params2 = new HashMap<String, String>();
            params2.put("body", replyMsg);
            try {
                mc.replyToThread(myId,id,params2);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);

            if (_dialog.isShowing()) 
                {
                    _dialog.dismiss();
                    Toast.makeText(MessageThreadReplyActivity.this, "Successfully sent",Toast.LENGTH_LONG).show();
                }
        }
    }

这是replyToThread方法:

public JSONObject replyToThread(String username, String threadId, HashMap<String, String> params) throws JSONException {
        return oClient.post("/mc/v1/threads/" + username + "/" + threadId, params);
        }

这是post方法:

public JSONObject post(String url, HashMap<String, String> params) throws JSONException {
        return sendPostRequest(url, METHOD_POST, params);
    }

这是sendPostRequest方法

private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params) throws JSONException {
        String fullUrl = getFullUrl(url);
        HttpPost request = new HttpPost(fullUrl);

        switch(type) {
        case METHOD_PUT:
        case METHOD_DELETE:
            // assign overload value
            String oValue;
            if (type == METHOD_PUT) {
                oValue = "put";
            } else {
                oValue = "delete";
            }
            params.put(OVERLOAD_PARAM, oValue);
        case METHOD_POST:
            break;
        default:
            throw new RuntimeException("Wrong http method requested");
        }

        // add parameters to request
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.size());

        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            nameValuePairs.add(new BasicNameValuePair(key, OAuth.percentEncode(value)));
            //nameValuePairs.add(new BasicNameValuePair(key,value));
        }
        try {
            request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // sign request
        try {
            mOAuthConsumer.sign(request);
        }
        catch (OAuthException e) {
            e.printStackTrace();
        }

        return oDeskRestClient.getJSONObject(request, type, params);
    }

最终的方法doPostRequest:

private static JSONObject doPostRequest(HttpPost httpPost, HashMap<String, String> params) throws JSONException {
        JSONObject json = null;
        //HttpClient postClient = HttpClientBuilder.create().build();
        DefaultHttpClient postClient = new DefaultHttpClient();
        HttpResponse response;

        try {
            response = postClient.execute(httpPost);

            if(response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    InputStream instream = entity.getContent();  
                    String result = convertStreamToString(instream);
                    instream.close();

                    json = new JSONObject(result);
                }
            } else {
                json = oDeskRestClient.genError(response);
            }
        } catch (ClientProtocolException e) {
            json = oDeskRestClient.genError(HTTP_RESPONSE_503, "Exception: ClientProtocolException");
        } catch (IOException e) {
            json = oDeskRestClient.genError(HTTP_RESPONSE_503, "Exception: IOException");
        } catch (JSONException e) {
            json = oDeskRestClient.genError(HTTP_RESPONSE_503, "Exception: JSONException");  
        } catch (Exception e) {
            json = oDeskRestClient.genError(HTTP_RESPONSE_503, "Exception: Exception " + e.toString());
        } finally {
            httpPost.abort();
        }

        return json;
    }

问题是我发送消息示例如

Hello how are you man
Hello%20how%20are%20you%20man

请帮助我,我不知道我错在哪里。

1 个答案:

答案 0 :(得分:0)

如果您可以确保 URL中的空格使其无效,那么您也可以使用' '进行char-by-char替换:

逐字符串替换为%20

URI uri = new URI(string.replace( "%20"," ",));

或者,如果您可以确保它只在最后一个斜杠之后需要编码的部分,那么您也可以这样做:

int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + URLEncoder.encode(string.substring(pos), "utf-8"));