无法使用Android

时间:2016-03-04 11:24:04

标签: android wordpress post httpurlconnection

更新:工作代码!

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 错误的内容是: {   "代码":" empty_content",   " message":"内容,标题和摘录都是空的。",   "数据":{     "状态":400   } }

1 个答案:

答案 0 :(得分:0)

这是解决方案!

Base64.encodeToString在编码用户的末尾添加一个\ n:pass,以使Header无效。

source