我要求在Web服务调用中将一些值从移动设备传递到服务器,因此我打算以JSON格式传递所有值,如下所示
{
"nameservice": [
{
"id": 7413,
"name": "ask"
},
{
"id": 7414,
"name": "josn"
},
{
"id": 7415,
"name": "john"
},
{
"id": 7418,
"name": "R&R"
}
]
}
以下是我的服务电话
@RequestMapping("/saveName")
@ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
);
System.out.println(acc);
jsonObject.accumulate("result", "saved ");
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
我试图通过这种方式调用上述服务
localhost:8080/service/saveName?acc={ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "R&R" } ] }
但是输出就像这样
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "R
任何人都能告诉我为什么我没有得到所有的价值观吗?
答案 0 :(得分:35)
我建议将正文中的JSON数据作为POST
请求传递。但是如果您仍想将其作为URL中的参数传递,则必须对URL进行编码,例如: -
是: - > {"name":"ABC","id":"1"}
testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D
有关URL编码的更多信息,请参阅下面的
答案 1 :(得分:13)
我知道这可能是后来的帖子,但是,对于新访问者,我将分享我的解决方案,因为OP要求通过GET传递JSON对象的方法(而不是其他答案中建议的POST)。
我在某些情况下使用过这种情况,我只能进行GET调用并且可以正常工作。此外,这个解决方案实际上是跨语言的。
答案 2 :(得分:3)
&安培;是这样的下一个参数的关键字 UR参数1 = 1&安培; param2的= 2
如此有效地发送名为R的第二个参数。你应该对你的字符串进行urlencode。是不是POST一个选项?
答案 3 :(得分:3)
您可以通过这种方式将json Input作为POST请求和授权标头传递
public static JSONObject getHttpConn(String json){
JSONObject jsonObject=null;
try {
HttpPost httpPost=new HttpPost("http://google.com/");
org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
StringEntity stringEntity=new StringEntity("d="+json);
httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
String authorization="test:test@123";
String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());
httpPost.addHeader("Authorization", security.get("Authorization"));
httpPost.setEntity(stringEntity);
HttpResponse reponse=client.execute(httpPost);
InputStream inputStream=reponse.getEntity().getContent();
String jsonResponse=IOUtils.toString(inputStream);
jsonObject=JSONObject.fromObject(jsonResponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
此方法将返回json响应。同样,您可以使用GET方法
答案 4 :(得分:2)
我知道这很老了,但是如果其他人想知道为什么为什么会得到上面不完整的json是因为与号&
是用于分隔参数的URL中的特殊字符。
在您的数据中,R&R
中有一个&号。因此,当acc参数达到&字符时结束。
这就是为什么您要获取切碎的数据。解决方案是对数据进行url编码,或者像公认的解决方案所建议的那样以POST形式发送。
答案 5 :(得分:0)
由于@ RE350建议在帖子中传递JSON数据是理想的。但是,您仍然可以将json对象作为参数发送到GET请求中,解码服务器端逻辑中的json字符串并将其用作对象。
例如,如果您使用的是php,则可以执行此操作(在其他语言中使用适当的json解码):
服务器请求:
http://<php script>?param1={"nameservice":[{"id":89},{"id":3}]}
在服务器中:
$obj = json_decode($_GET['param1'], true);
$obj["nameservice"][0]["id"]
out put:
89
答案 6 :(得分:0)
将Json数据字符串发送到网址并使用方法发布
获得结果在C#中
public string SendJsonToUrl(string Url, string StrJsonData)
{
if (Url == "" || StrJsonData == "") return "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = StrJsonData.Length;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(StrJsonData);
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
}
catch (Exception exp)
{
throw new Exception("SendJsonToUrl", exp);
}
}
PHP中的
<?php
$input = file_get_contents('php://input');
$json = json_decode($input ,true);
?>
答案 7 :(得分:0)
我知道这可能是以后的帖子,但是,对于新访问者,我将分享我的解决方案,因为OP要求通过GET传递JSON对象的方法(而不是其他答案中建议的POST)
1.JSON对象并将其转换为字符串(JSON.stringify) 2.字符串并在Base64中编码(您可以在此处找到一些有用的信息
答案 8 :(得分:0)
let qs = event.queryStringParameters;
const query = Object.keys(qs).map(key => key + '=' + qs[key]).join('&');
答案 9 :(得分:0)
我遇到了同样的需求,并提出了一个适用于Next.js框架的通用解决方案(node + browser)。
它与循环依赖项一起工作。虽然,我还在其之上构建了一个序列化程序以删除不必要的数据(因为不建议使用长度超过2k个字符的网址,请参见What is the maximum length of a URL in different browsers?)
import StringifySafe from 'json-stringify-safe';
export const encodeQueryParameter = (data: object): string => {
return encodeURIComponent(StringifySafe(data)); // Use StringifySafe to avoid crash on circular dependencies
};
export const decodeQueryParameter = (query: string): object => {
return JSON.parse(decodeURIComponent(query));
};
单元测试(开玩笑):
import { decodeQueryParameter, encodeQueryParameter } from './url';
export const data = {
'organisation': {
'logo': {
'id': 'ck2xjm2oj9lr60b32c6l465vx',
'linkUrl': null,
'linkTarget': '_blank',
'classes': null,
'style': null,
'defaultTransformations': { 'width': 200, 'height': 200, '__typename': 'AssetTransformations' },
'mimeType': 'image/png',
'__typename': 'Asset',
},
'theme': {
'primaryColor': '#1134e6',
'primaryAltColor': '#203a51',
'secondaryColor': 'white',
'font': 'neuzeit-grotesk',
'__typename': 'Theme',
'primaryColorG1': '#ffffff',
},
},
};
export const encodedData = '%7B%22organisation%22%3A%7B%22logo%22%3A%7B%22id%22%3A%22ck2xjm2oj9lr60b32c6l465vx%22%2C%22linkUrl%22%3Anull%2C%22linkTarget%22%3A%22_blank%22%2C%22classes%22%3Anull%2C%22style%22%3Anull%2C%22defaultTransformations%22%3A%7B%22width%22%3A200%2C%22height%22%3A200%2C%22__typename%22%3A%22AssetTransformations%22%7D%2C%22mimeType%22%3A%22image%2Fpng%22%2C%22__typename%22%3A%22Asset%22%7D%2C%22theme%22%3A%7B%22primaryColor%22%3A%22%231134e6%22%2C%22primaryAltColor%22%3A%22%23203a51%22%2C%22secondaryColor%22%3A%22white%22%2C%22font%22%3A%22neuzeit-grotesk%22%2C%22__typename%22%3A%22Theme%22%2C%22primaryColorG1%22%3A%22%23ffffff%22%7D%7D%7D';
describe(`utils/url.ts`, () => {
describe(`encodeQueryParameter`, () => {
test(`should encode a JS object into a url-compatible string`, async () => {
expect(encodeQueryParameter(data)).toEqual(encodedData);
});
});
describe(`decodeQueryParameter`, () => {
test(`should decode a url-compatible string into a JS object`, async () => {
expect(decodeQueryParameter(encodedData)).toEqual(data);
});
});
describe(`encodeQueryParameter <> decodeQueryParameter <> encodeQueryParameter`, () => {
test(`should encode and decode multiple times without altering data`, async () => {
const _decodedData: object = decodeQueryParameter(encodedData);
expect(_decodedData).toEqual(data);
const _encodedData: string = encodeQueryParameter(_decodedData);
expect(_encodedData).toEqual(encodedData);
const _decodedDataAgain: object = decodeQueryParameter(_encodedData);
expect(_decodedDataAgain).toEqual(data);
});
});
});