这是我的 HTTP 网址
POST HTTPS://www.googleapis.com/admin/directory/v1/group
MY json request
{
"email": "sales_group@example.com",
"name": "Sales Group",
"description": "This is the Sales group."
}
我正在使用 Directory API 创建组。
到目前为止,我从未使用过 URL fetch,所以我对此并不熟悉。请帮助我我该怎么做..
这是我在 2 小时后发布的答案。由于我的声誉少于 10,stackoverflow 不允许我在 8 小时之前回答我自己的问题,所以请原谅我的长问题。我试过这个..我在将json作为参数传递时有点挣扎。这是我的代码
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;
import javax.servlet.http.*;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
@SuppressWarnings("serial")
public class DirectoryApiExampleServlet extends HttpServlet {
static Logger log = gger.getLogger(DirectoryApiExampleServlet.class.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
URL url = new URL("https://www.googleapis.com/admin/directory/v1/groups");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
JSONObject json = new JSONObject();
try {
json.put("email", "abc@gmail.com");
json.put("name", "Test Group");
json.put("description", "this is a test group");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
writer.write(json.toString());
writer.flush();
writer.close();
log.info("connection.getResponseCode()"+connection.getResponseCode());
}
}
但它给出了 401 响应,这是意料之外的。
我在哪里犯错???