如何用Java发布 [英] How to POST in Java

查看:100
本文介绍了如何用Java发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的东西:

I have something that looks like this:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

grant_type=assertion&assertion_type=http%3A%2F%2Foauth.net%2Fgrant_type%2Fjwt%2F1.0%2Fbearer&assertion=eyJhbGciOiJSUzI1NiIs

我将如何在Java中使用它?我已经掌握了所有信息,因此无需解析.

How would I go about using this in Java? I have all the information already so I wouldn't need to parse it.

基本上,我需要使用3种不同的数据进行POST,并且使用curl一直在为我工作,但是我需要在java中完成它:

Basically I need to POST with 3 different data and using curl has been working for me but I need to do it in java:

curl -d 'grant_type=assertion&assertion_type=http%3A%2F%2Foauth.net%2Fgrant_type%2Fjwt%2F1.0%2Fbearer&assertion=eyJhbGciOiJSUzI1NiIsInR5i' https://accounts.google.com/o/oauth2/token

我切断了一些数据,使其更易于阅读,因此无法正常工作.

I cut off some data so its easier to read so it wont work.

一个大问题是,卷曲会起作用,而我尝试使用Java的大多数教程会给我HTTP响应错误400.

So a big problem is that the curl would work while most tutorials I try for Java would give me HTTP response error 400.

就像我应该像这样对日期进行编码:

Like should I be encoding the date like this:

String urlParameters = URLEncoder.encode("grant_type", "UTF-8") + "="+ URLEncoder.encode("assertion", "UTF-8") + "&" + URLEncoder.encode("assertion_type", "UTF-8") + "=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&" + URLEncoder.encode("assertion", "UTF-8") + "=" + URLEncoder.encode(encodedMessage, "UTF-8");

还是不:

String urlParameters ="grant_type=assertion&assertion_type=http://oauth.net/grant_type/jwt/1.0/bearer&assertion=" + encodedMessage;

使用此代码:

URL url = new URL(targetURL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);


OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
     System.out.println(line);
}
writer.close();
reader.close();

推荐答案

使用类似 HttpClient 或类似的文件.

Use something like HttpClient or similar.

它可以将经过URL预先编码的数据发布到URI,尽管我不知道您是否可以向其扔一个完整的请求正文-可能需要解析它,但是可能有一些库可以将其解析为好吧.

It can post pre-URL-encoded data to a URI, although I don't know if you could just throw a complete request body at it--might need to parse it out, but there are likely libraries for that as well.

这篇关于如何用Java发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆