0
已更新:工作代碼!無法使用Android的wp-API POST請求
static public HttpURLConnection HTTPconnectionPOST(String url_api, String name, String password,String method) throws IOException {
URL url = new URL(url_api);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
String urlParameters = "Content=Testing&title=TheTest";
connection.setRequestMethod("POST");
String userCredentials = name+":"+password;
connection.addRequestProperty("Authorization", "Basic " + Base64.encodeToString((name + ":" + password).getBytes(), Base64.DEFAULT).trim());
connection.setRequestProperty("Host", "localhost");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
dStream.flush();
dStream.close();
connection.connect();
return connection;
}
下面是我使用,使POST請求代碼:
static public HttpURLConnection HTTPconnectionPOST(String url_api, String name, String password,String method) throws IOException {
URL url = new URL(url_api);
System.out.println(url_api);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
String userCredentials = name+":"+password;
String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes(),Base64.DEFAULT));
urlConnection.setRequestProperty("Host", "localhost");
urlConnection.setRequestProperty ("Authorization", basicAuth);
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
/* optional request header */
urlConnection.setRequestProperty("Content-Type", "application/json");
/* optional request header */
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setConnectTimeout (30000) ;
urlConnection.setDoOutput(true);
String a="testing";
String b="test";
String c="test";
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("Content", a)
.appendQueryParameter("title", b)
.appendQueryParameter("excerpt", c);
String query = builder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query.toString());
writer.flush();
writer.close();
os.close();
System.out.println(query);
urlConnection.connect();
return urlConnection;
}
爲響應這就是我得到: 無法發佈數據400 而errorstream內容: { 「code」:「empty_content」, 「message」:「Content,title and excerpt are empty。」, 「data」:{ 「status」:4 00 } }