使用Java&提交带参数和正文的POST请求休息

时间:2017-05-02 16:41:33

标签: java rest servlets post httprequest

我正在尝试使用现有的API来调用json对象使用POST“提交”,但该页面在请求中也需要一些参数,对于此示例,我们将使用名称和电子邮件。我是REST的新手,所以我可能在这里的某个地方犯了一个无知的错误。

这是我到目前为止在servlet中的代码:

String path = "http://www.test.com/submit";
URL url = new URL(path);
conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");

Gson gson = new Gson();

//julySchedule is the object I want to submit with this request alongside the parameters.
String input = gson.toJson(julySchedule);

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();

if (conn.getResponseCode() != 200) {
    throw new RuntimeException("HTTP POST Request Failed with Error code : "
                    + conn.getResponseCode());
        }

我试图将参数放在网址中,例如:

/submit?name=Name&email=test@gmail.com

但这没有用,因为POST请求不会接受这样的参数。 然后我尝试将它添加到输出流中,如:

String params = "name=Name&email=test@gmail.com"
OutputStream os = conn.getOutputStream();
os.write(path.toBytes());
os.write(input.getBytes());
os.flush();  

但这也不起作用。我在某个地方犯了一个非常愚蠢的错误吗?

1 个答案:

答案 0 :(得分:0)

POST请求包含查询字符串完全没问题(尽管不是最佳实践)。

由于您使用from sys import argv # this argument will import argument variables from os.path import exists files_12 = "{} {}" print (files_12.format(1, 2)) script, test1, test2, test3 = argv # here i get arguments target1 = open(test1) # this opens test1 and variable set at target1 new_target = target1.read() # this reads target1 which is originally test1 print (f"Number of strings in target1 is {len(new_target)}") # in this i have given print to count number of strings in test1, why new target because i have assigned variable of new_target in read print (f"Does the out file exist? {exists(test2)}") # this will check if if exist or not target2 = open(test2, "w") # this will open test2 target2.write(new_target)# this will write data of test1 in test2 target3 = open(test2) # this will pen test2 veerynew = target3.read()# this will read test2 target_new = open(test1, "w") #this will open test1 in write mode which is put by "r" target_new.truncate()# this will clead data of test1 target4 = open(test3, "w")# this will open test3 target4.write(veerynew)#this will write data of test2 in test2 target1.close()# this will close file 1 target2.close()#this will close file 2 target3.close()#this will close file 3 target4.close()#this will close file 4 作为application/json,我假设您的有效负载必须是JSON对象。你不能在POST体内混合你的参数。您有两个选择:

  1. 在QueryString中使用Kep电子邮件和名称,在POST有效负载中使用json:您所做的应该有效。
  2. 仅使用POST有效内容:设置Content-Type Content-Type:,如下所示:application/x-www-form-urlencoded。服务器应从POST有效负载中提取name=NAME&email=EMAIL&jsonPayLoad={Your Json Object}
  3. 确保在写入POST输出流之前使用jsonPayLoad进行转义。