用java這是我的HTTP URL我需要使用json請求進行java.net url的獲取。請告訴我,我怎麼能叫,在谷歌的AppEngine
POST HTTPS://www.googleapis.com/admin/directory/v1/group
MY json request
{
"email": "[email protected]",
"name": "Sales Group",
"description": "This is the Sales group."
}
我使用目錄API來創建組。
我從來沒有使用URL獲取,所以我不熟悉這一點。 請幫我,我該怎麼做..
這是我的答案我發佈後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", "[email protected]");
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響應。
我在哪裏犯錯誤?
我在我的問題回答本身,請閱讀。 – Bharathi
401是由於您未經授權的事實。在調用API之前,您需要使用允許執行該操作的正確憑據進行登錄。請參閱特定API的文檔。 – Romin