当您使用REST使用POST创建新条目时,我看到一些API(例如Google)指定您将XML作为请求的一部分发送,而其他API 则指定您发送键/值对.REST POST是否有标准或最佳实践?
这是我从其中一个Web服务收到的示例字符串,
body=%7B%22type%22%3A%22change%22%2C%22url%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ftriggers%2F4100%22%2C%22environment%22%3A%7B%22feed%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ffeeds%2F36133%22%2C%22title%22%3A%22Current+Cost+Bridge%22%2C%22description%22%3Anull%2C%22id%22%3A36133%7D%2C%22threshold_value%22%3Anull%2C%22timestamp%22%3A%222012-01-05T09%3A27%3A01Z%22%2C%22triggering_datastream%22%3A%7B%22url%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ffeeds%2F36133%2Fdatastreams%2F1%22%2C%22value%22%3A%7B%22value%22%3A%22523%22%2C%22max_value%22%3A1269.0%2C%22min_value%22%3A0.0%7D%2C%22id%22%3A%221%22%2C%22units%22%3A%7B%22symbol%22%3A%22W%22%2C%22type%22%3A%22derivedUnits%22%2C%22label%22%3A%22watts%22%7D%7D%2C%22id%22%3A4100%7D
Run Code Online (Sandbox Code Playgroud)
这是代码,
class Feeds():
def GET(self):
print "Get request is accepted."
return render.index(None)
def POST(self):
print "Post request is accepted."
print (web.data())
Run Code Online (Sandbox Code Playgroud)
现在,当该Web服务发布上述给定数据时,我将如何将其转换为可读格式?然后,我需要将其转换为JSON对象并进一步使用.那么,我将如何转换它?
当我尝试这段代码时,
json_data = json.loads(web.data())
print json_data['body']
return render.index(json_data['body'])
Run Code Online (Sandbox Code Playgroud)
它给了我一个错误,
enter code Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/web/application.py", line 237, in process
return self.handle()
File "/usr/local/lib/python2.6/dist-packages/web/application.py", line 228, in handle
return self._delegate(fn, self.fvars, args)
File "/usr/local/lib/python2.6/dist-packages/web/application.py", line 409, in _delegate
return handle_class(cls)
File "/usr/local/lib/python2.6/dist-packages/web/application.py", line 385, in handle_class
return tocall(*args)
File "/home/ubuntu/pachubeConsumer/src/controllers/feeds.py", line 17, in POST …Run Code Online (Sandbox Code Playgroud) 我正在编写我的第一个谷歌浏览器扩展程序,它将使用谷歌的URL缩短器api来缩短Chrome中当前活动选项卡的URL.
我是一个长期的开发人员(asm/C++),但对于这个"webby"的东西来说是全新的.:)
我似乎无法弄清楚如何使用js或jquery制作(然后处理)http POST请求.我想我只是不理解curl示例之外的POST机制.
我的javascript文件目前看起来像这样:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('chrome.browserAction.onClicked.addListener');
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url;
console.log(tablink);
//TODO send http post request in the form
// POST https://www.googleapis.com/urlshortener/v1/url
// Content-Type: application/json
// {"longUrl": "http://www.google.com/"}
});
Run Code Online (Sandbox Code Playgroud)
});
我是Android新手,我正在使用Google GCM发送纯文本消息.是否可以将图像文件作为流或其他方法发送?
Java - 服务器
Android - 客户端.
Message message = new Message.Builder()
.collapseKey("1")
.timeToLive(3)
.delayWhileIdle(true)
.addData("TEST",
"Hello Android")
.build();
Run Code Online (Sandbox Code Playgroud)
这里的简单信息是.addData("TEST","Hello Android").
android servlets http-post push-notification google-cloud-messaging
我正在寻找有关如何在Android上使用HttpPost方法发送信息的信息,我总是看到:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Name","Var1"));
params.add(new BasicNameValuePair("Name2","Var2"));
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
Run Code Online (Sandbox Code Playgroud)
问题是我无法做到这一点,因为我必须连接到接收XML格式的String的资源.
关于如何在不使用字符串的情况下仅发送字符串的任何想法 List<nameValuePair>
我知道这个问题已经有问题,但我还是不能正确地做到这一点.需要一些帮助.
我需要上传一个带有附加数据的文件.
我的input.php:
<input type="file" id="foto_path" name="foto_path" />
<input type="button" value="Add" onclick="javascript:sendForm()" />
Run Code Online (Sandbox Code Playgroud)
我用javascript发送:
function sendForm() {
var fileInput = document.querySelector('#foto_path');
var oMyForm = new FormData();
var nip=123223374;//it will be generated by php, for temporary i just hardcode it
oMyForm.append("foto_path", fileInput);
oMyForm.append("nip",nip );
var oReq = new XMLHttpRequest();
oReq.open("POST", "upload-file.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
//oOutput.innerHTML = "Uploaded!";
alert('success');
} else {
//oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>"; …Run Code Online (Sandbox Code Playgroud) 我想从我的应用程序发出以下请求:
AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
requestManager.responseSerializer.acceptableContentTypes = [requestManager.responseSerializer.acceptableContentTypes setByAddingObject:@"application/json"];
requestManager.requestSerializer = [AFJSONRequestSerializer serializer];
[requestManager POST:urlString parameters:aParameters constructingBodyWithBlock:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"%@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"error: %@", error);
}];
Run Code Online (Sandbox Code Playgroud)
其中aParameters是具有以下内容的NSDictionary:
NSDictionary *urlParams = @{@"username" : anUser.userName, @"password" : anUser.password};
Run Code Online (Sandbox Code Playgroud)
当我使用用户输入"anUsername"和"aPassword"从我的应用程序发出请求时,我在servlet中获取了以下日志:
--Boundary+5738A89B2C391231
Content-Disposition: form-data; name="password"
aPassword
--Boundary+5738A89B2C391231
Content-Disposition: form-data; name="username"
anUsername
--Boundary+5738A89B2C391231--
multipart/form-data; boundary=Boundary+5738A89B2C391231
Run Code Online (Sandbox Code Playgroud)
我的印象是使用AFJSONRequestSerializer会以适当的格式发送我的请求,但是正如日志所示,它是多部分/表单数据.解析这种请求真的很难(对我来说)(我在服务器端用Java解析它),所以我的问题是:是否有可能在我的请求正文中发送一个json?像这样的东西:
{
"userName" : "anUsername",
"password" : "aPassword"
}
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激.
我有一个启用OAuth2的站点,它遇到了与IE如何处理303响应有关的问题.在流程中,发生3次重定向.
### Chrome/Firefox
POST idp.com/login (res 302 -> idp.com/authenticate)
GET idp.com/authenticate (res 302 -> app.com/oauth2/callback)
GET app.com/oauth2/callback (res 303 -> app.com/home)
GET app.com/home
### IE
POST idp.com/login (res 302 -> idp.com/authenticate)
POST idp.com/authenticate (res 302 -> app.com/oauth2/callback)
POST app.com/oauth2/callback (res 303 -> app.com/home)
POST app.com/home
Run Code Online (Sandbox Code Playgroud)
由于某种原因,IE似乎维护了原始的请求方法.我尝试通过返回303来至少从我的服务器(app.com)上的原始POST响应中断,但这也没有解决问题.这是意料之外的,因为RFC 2068声明对于303 - See Other响应,应遵循以下内容
可以在不同的URI下找到对请求的响应,并且应该使用该资源上的GET方法检索.此方法主要用于允许输出POST激活的脚本以将用户代理重定向到选定的资源.
我甚至尝试了307响应但没有成功.有没有人对这里发生的事情有任何想法?
这是我第一次发送多部分请求,在这里挖掘之后,我变得更加困惑,所以任何有关"正确"方式的帮助都会非常受欢迎.
我有一个函数,应该得到:文件路径和JSON的String表示,并使用multipart向服务器发送POST请求.
我不知道何时使用boundary和"multipart/form-data"内容类型之间的差异addPart和addTextBody,当(为什么),它总是被写入Content-Disposition: form-data; name=\
public String foo(String filePath, String jsonRep, Proxy proxy)
{
File f = new File(filePath);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection(proxy);
connection.setRequestProperty("Content-Type", "multipart/form-data"); // How should I generate boundary? Should it be added here?
if (myMethod == "POST")
{
connection.getOutputStream().write( ? Both the json string and the file bytes?? );
}
.... checking there is no error code etc..
return ReadResponse(connection) // read input stream..
Run Code Online (Sandbox Code Playgroud)
现在我不知道如何继续,以及如何编写文件和json字符串我看到这段代码:
MultipartEntityBuilder …Run Code Online (Sandbox Code Playgroud) 我试图将我的Node JS应用程序中的图像发布到另一个REST API.我有Mongo DB中的图像(作为二进制数组数据),由Node JS读取,然后应该发布到另一个API.
我面临的问题是如何与图像一起发送请求数据?我有这个原始数据(采用JSON格式),应与图像一起发布:
{"data":{"client":"abc","address": "123"},"meta":{"owner": "yourself","host": "hostishere"}}
Run Code Online (Sandbox Code Playgroud)
我需要使用'request'模块执行此操作.如果有更好的帮助,我可以使用'multer'.但是,我仍然坚持如何将上述请求数据与图像流一起发送.以下是我目前的代码.你能帮帮我完成吗?
var options = {
host: 'hostname.com',
port: 80,
path: '/api/content',
method: 'POST',
headers:{
'Content-Type' : 'multipart/form-data'
}
};
var request = http.request(options, function(response) {
var str = '';
var respTime ='';
response.on('data', function (chunk) {
str = str.concat(chunk);
});
response.on('end', () => {
console.log('No more data in response.');
});
setTimeout(function() {
res.send(JSON.stringify(
{
'imageURL': IMG_URL,
'imageId': IMG_ID,
'body': JSON.parse(str)
}
));
}, 1000);
});
request.on('error', (e) => {
console.error('**** …Run Code Online (Sandbox Code Playgroud)