1

我有一个要求,我必须在 url 中传递一个 json 对象作为参数。这是我的网址

http://test.amazonaws.com/xyx/company/12/user/1/contact/{contactActivityJSON}/key/abccedrf/contacts?op=readsave

现在contactActivityJSON具有以下结构

{
    "user": {},
    "event": {
        "id": 1,
    },
    "contacts": [
        {
            "id": "-1",
            "eventId": 1,
            "fields": [
                {
                    "fieldName": "test",
                    "value": "CallMe"
                }
            ]
        }
    ]
}

现在我在将 JSON 对象编码到 URL 时遇到问题。我在用

ObjectMapper mapper = new ObjectMapper();
Writer strWriter = new StringWriter();
mapper.writeValue(strWriter, request.getRequestBody());
String jsonString = strWriter.toString();
String sss = URLEncoder.encode(jsonString);

并将其替换为 URL。但它不起作用。有人可以帮忙吗?

4

1 回答 1

-1

我猜你是在 JsonObject 上发布到服务器。使用下面的代码它对我来说很好

    /**
 * Uplaod with Json Object
 * 
 * @param _requestedURL
 * @param obj
 * @return
 * @throws IOException
 */
public String UploadUrl(String _requestedURL, JSONObject obj)
        throws IOException {
    HttpPost _request = new HttpPost(_requestedURL);
    HttpResponse _response = null;
    DefaultHttpClient _httpClient = new DefaultHttpClient();
    String _ContetnString = null;
    try {
        StringEntity se = new StringEntity(obj.toString());
        _request.setEntity(se);
        _request.setHeader("Accept", "application/octet-stream");
        _request.setHeader("Content-type", "application/octet-stream");
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                CommonValues.TIME_OUT);
        HttpConnectionParams.setSoTimeout(httpParameters,
                CommonValues.TIME_OUT);
        _request.setParams(httpParameters);
        _response = _httpClient.execute(_request);
        if (_response != null
                && _response.getStatusLine().getStatusCode() == 200) {
            //Read Responce
        }
    } catch (SocketException e) {
    } catch (ConnectTimeoutException e) {
    } catch (Exception e) {
    }

    return _ContetnString;
}
于 2013-08-21T12:27:56.207 回答