我正在使用JSON请求调用REST服务,它给出了Http 415"不支持的媒体类型"错误.
请求内容类型设置为("Content-Type","application/json; charset = utf8").
如果我在请求中不包含Json对象,它可以正常工作.我正在为json使用google-gson-2.2.4库.
我尝试使用几个不同的库,但它没有任何区别.
有人可以帮我解决这个问题吗?
这是我的代码:
public static void main(String[] args) throws Exception
{
JsonObject requestJson = new JsonObject();
String url = "xxx";
//method call for generating json
requestJson = generateJSON();
URL myurl = new URL(url);
HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=utf8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Method", "POST");
OutputStream os = con.getOutputStream();
os.write(requestJson.toString().getBytes("UTF-8"));
os.close();
StringBuilder sb = new StringBuilder();
int HttpResult =con.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
String line = null;
while …Run Code Online (Sandbox Code Playgroud) 我有一些我需要转换为C#的JavaScript代码.我的JavaScript代码将一些JSON发布到已创建的Web服务.此JavaScript代码工作正常,如下所示:
var vm = { k: "1", a: "2", c: "3", v: "4" };
$.ajax({
url: "http://www.mysite.com/1.0/service/action",
type: "POST",
data: JSON.stringify(vm),
contentType: "application/json;charset=utf-8",
success: action_Succeeded,
error: action_Failed
});
function action_Succeeded(r) {
console.log(r);
}
function log_Failed(r1, r2, r3) {
alert("fail");
}
Run Code Online (Sandbox Code Playgroud)
我正在试图找出如何将其转换为C#.我的应用程序使用的是.NET 2.0.据我所知,我需要做以下事情:
using (WebClient client = new WebClient())
{
string json = "?";
client.UploadString("http://www.mysite.com/1.0/service/action", json);
}
Run Code Online (Sandbox Code Playgroud)
我现在有点卡住了.我不确定json应该是什么样的.我不确定是否需要设置内容类型.如果我这样做,我不知道该怎么做.我也看到了UploadData.所以,我不确定我是否使用了正确的方法.从某种意义上说,我的数据序列化是我的问题.
谁能告诉我我在这里失踪了什么?
谢谢!
看起来像json默认编码是UTF-8 Spring mvc默认返回"application/json; charset = utf-8"并且很难改变它.
在我的$ .ajaxSucess()函数中,我需要找出响应是否为json.目前我这样做:
$('body').ajaxSuccess(function(evt, xhr, settings) {
var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/);
if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){
...
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
我有一个Sinatra应用程序(http://analyzethis.espace-technologies.com)执行以下操作
所以我在尝试阅读使用windows-1256编码的网站时遇到了这个问题,例如www.filfan.com或www.masrawy.com.
问题是虽然没有抛出错误,但编码转换的结果不正确.
net/http response.body.encoding给出ASCII-8BIT,它不能转换为UTF-8
如果我做Nokogiri :: HTML(response.body)并使用css选择器从页面获取某些内容 - 例如标题标签的内容 - 我得到一个字符串,当我调用string.encoding返回WINDOWS-1256 .我使用string.encode("utf-8")并使用它发送响应,但同样响应不正确.
关于我的方法有什么问题的任何建议或想法?
我使用Python的requests库编写了一个特定的API包装器.
当它获得响应时requests.get,它会尝试解析为json并获取原始内容(如果它不起作用):
resp = requests.get(url, ...)
try:
resp_content = resp.json()
except ValueError:
resp_content = resp.content
return resp_content
Run Code Online (Sandbox Code Playgroud)
这对我的目的是正确的.问题是下载的响应是图像文件需要多长时间,例如,如果它很大,那么在输入try和失败json解析并输入之前需要很长时间except.
(我不知道是否需要超长时间来.json()完成错误,或者如果一旦错误则需要一段时间才能进入except.)
有没有办法看看是否respjson可解析而不试图解析它.json()?有点像resp.is_json,所以我可以立即知道要采取(resp.json()或resp.content)哪个分支,而不是等待30秒(大文件可能需要几分钟).
编辑:
如上所述,这种缓慢对于requestsjson解析来说并不常见.它可能与我收到的数据的性质有关(它来自Salesforce REST API,检索Attachment对象的'Body'字段).
即使这是一种解决方法,我也会将我的解决方案放在这里,以防该策略帮助其他任何人.我意识到我正在进行调用,我通常知道我是否希望响应是二进制数据,所以我可以将一个关键字参数传递给我的包装函数,告诉它跳过json解析尝试.
def SalesforceWrapper(..., attempt_json=True):
resp = requests.get(url, ...)
try:
if attempt_json:
resp_content = resp.json()
else:
resp_content = resp.content
except ValueError:
resp_content = resp.content
return resp_content
Run Code Online (Sandbox Code Playgroud)
attempt_json=False当我希望响应是文件的数据而不是lil JSON响应时,我会通过.
我正在向服务器发送请求,并在响应中获取Collection + Json。PostMan中的每件事都是完美的。
但是,当我使用OKHTTP在代码中执行相同的操作时,我得到了一些不可读的字符。
这是我的代码
OkHttpClient client = new OkHttpClient();
requestBody = new FormBody.Builder()
.add("email", email)
.add("password", psd)
.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Accept", "application/vnd.collection+json")
.addHeader("Accept-Encoding", "gzip")
.addHeader("Authorization", "Basic YWRtaW46cmVhbHNlYw==")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String s = response.body().string();
response.body().close();
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
我尝试了其他一些网址,但它们运行正常。
非常感谢。
为了便于可视化,下面是记录查找表。
我似乎在网上找不到任何地方可以告诉您其中哪些应该还包含charset=utf-8.
我应该假设它与文本类似吗?
看一看:
const MEDIA_TYPES: Record<string, string> = {
".md": "text/markdown",
".html": "text/html",
".htm": "text/html",
".json": "application/json",
".map": "application/json",
".txt": "text/plain",
".ts": "text/typescript",
".tsx": "text/tsx",
".js": "application/javascript",
".jsx": "text/jsx",
".gz": "application/gzip",
".css": "text/css",
".wasm": "application/wasm",
".mjs": "application/javascript",
".otf": "font/otf",
".ttf": "font/ttf",
".woff": "font/woff",
".woff2": "font/woff2",
".conf": "text/plain",
".list": "text/plain",
".log": "text/plain",
".ini": "text/plain",
".vtt": "text/vtt",
".yaml": "text/yaml",
".yml": "text/yaml",
".mid": "audio/midi",
".midi": "audio/midi",
".mp3": "audio/mp3",
".mp4a": "audio/mp4",
".m4a": "audio/mp4",
".ogg": "audio/ogg",
".spx": "audio/ogg",
".opus": "audio/ogg",
".wav": "audio/wav", …Run Code Online (Sandbox Code Playgroud) 我需要从Delphi客户端向Restful datasnap服务器(Delphi)发送一个简单的JSON对象.我正在使用Delphi XE.任何人都可以帮我解决问题吗?我想要几个小时,但没有得到它..请问问,如果细节不够
编辑:这是服务器端方法声明:
procedure updatemethodnme(str:string):string;
Run Code Online (Sandbox Code Playgroud)
这是客户端代码:
function PostData(request: string): boolean;
var
param: TStringList;
url, Text,str: string;
code: Integer;
http: TIDHttp;
begin
Result:= false;
http:= TIDHttp.Create(nil);
http.HandleRedirects:= true;
http.ReadTimeout:= 50000;
http.request.Connection:= 'keep-alive';
str:= '{"lamp":"'+lamp+'","floor":"'+floor+'","op":"'+request+'"}';
param:= TStringList.Create;
param.Clear;
param.Add(str);
url:= 'h***p://xx2.168.xx.xx:xxxx/Datasnap/rest/TserverMethods1/methdname/';
try
Text:= http.Post(url, param);
Result:= true;
except on E: Exception do
begin
Result := false;
end;
end;
end;
Run Code Online (Sandbox Code Playgroud) 我从我的数据库中获取了一个学校列表及其相应的列,这些列有1000多行,然后将其转换为JSON并将其传递给我的视图并使用它解析它
$.parseJSON('@Html.Raw(Model.subChoiceJsonString)')
Run Code Online (Sandbox Code Playgroud)
然后将它放到一个数组
ko.observableArray($.parseJSON('@Html.Raw(Model.subChoiceJsonString)'));
Run Code Online (Sandbox Code Playgroud)
但我的问题是它不起作用,但是当行数小得多时它就可以工作.
我认为由于Javascript中字符串的限制,它无法解析.那是对的吗?我怎样才能使它工作?
json ×4
http ×3
javascript ×3
ajax ×1
android ×1
c# ×1
datasnap ×1
delphi ×1
deno ×1
encoding ×1
java ×1
jquery ×1
knockout.js ×1
mime-types ×1
okhttp3 ×1
python ×1
rest ×1
ruby ×1
ruby-1.9 ×1
sinatra ×1
spring-mvc ×1
typescript ×1
web-services ×1
webclient ×1