我在哪裡將 REST 客戶端身份驗證數據放在查詢中? (Where do I put the REST Client Authentication Data in the Query?)


問題描述

我在哪裡將 REST 客戶端身份驗證數據放在查詢中? (Where do I put the REST Client Authentication Data in the Query?)

I need to work with REST api in android application which is created by my client. Below text is just copied from the pdf the client provides us.

‑‑
In this example, a new user is created. The parts of a possible request to the server is shown below:

Message part Contents

Header POST {url‑prefix}/rest/user
Content‑Type: application/xml
Content‑Length: 205
Body <request>
  <client>
    <id>XY</id>
    <name>myName</name>
    <password>myPassword</password>
  </client>
  <user>
    <name>myUserName</name>
    <password>myUserPassword</password>
    <groupId>12345</groupId>
  </user>
</request>

‑‑
After searching and studying, I come to know that, the possible request code (in Java) might be:

URL url=new URL("http://api.example.com/rest/user/?name=myUserName&password=myUserPassword&groupId=12345");
            HttpURLConnection conn=(HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("Post");
            OutputStreamWriter out=new OutputStreamWriter(conn.getOutputStream());
            out.write("respose content:");
            out.close();

From the pdf manual they provide, I got to know, for every request to the server, the client (thats me) has to transmit  the authentication data.
My question is, where do I put the authentication data in the query string? Please help me on this. 

Edit:After posting the below code as request:

            DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://api.example.com/rest/user/?name=Foysal&password=123456&groupid=12345");
            httpPost.addHeader("Accept", "text/xml");
            httpPost.setHeader("Content‑Type","application/xml;charset=UTF‑8");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", "APIappDevAccount"));
            nameValuePairs.add(new BasicNameValuePair("password", "123456"));           
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setStaleCheckingEnabled(params, false);
            HttpConnectionParams.setConnectionTimeout(params, 5000);
            HttpConnectionParams.setSoTimeout(params, 5000);
            httpClient.setParams(params);
            httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
            HttpResponse response = httpClient.execute(httpPost);
            InputStream is = response.getEntity().getContent();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] buf;
            int ByteRead;
            buf = new byte[1024];
            String xmldata = null;
            double totalSize = 0;
            while ((ByteRead = is.read(buf, 0, buf.length)) != ‑1) {
                os.write(buf, 0, ByteRead);
                totalSize += ByteRead;                      
            }
            xmldata =  os.toString();
            os.close();
            is.close();


But I got the response as:

  

  404   Not Found    

Not Found

 

The requested   URL /rest/user/ was not found on this   server.

 
Apache/2.2.6   (Fedora) DAV/2 mod_ssl/2.2.6   OpenSSL/0.9.8b Server at    api.example.com Port 80   

‑‑‑‑‑

參考解法

方法 1:

Looks to me like they want you to POST an XML document and put the authentication in that. Not much of a REST API (most REST APIS don't require an XML document).

You need to use conn.getOutputStream() to send that doc to the server and use conn.getInputStream() to read the response.

So you would have to create the XML doc like the one they show:

<request>
  <client>
    <id>XY</id>
    <name>myName</name>
    <password>myPassword</password>
  </client>
  <user>
    <name>myUserName</name>
    <password>myUserPassword</password>
    <groupId>12345</groupId>
  </user>
</request>

And then send it in your POST:

conn.setRequestProperty ( "Content‑Type", "text/xml" );
out.write(requestDoc); //where requestDoc is the String containing the XML.
out.flush();
out.close();

方法 2:

You may execute a POST request like shown here: http://www.androidsnippets.com/executing‑a‑http‑post‑request‑with‑httpclient and put the authentication data as name value pairs:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("name", "myUserName"));
    nameValuePairs.add(new BasicNameValuePair("password", "myUserPassword"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (Exception e) {
    // ... handle exception here
}

(by Foyzul KarimFraggleTim Büthe)

參考文件

  1. Where do I put the REST Client Authentication Data in the Query? (CC BY‑SA 3.0/4.0)

#java #HTTP #restful-authentication #REST #Android






相關問題

電子郵件地址中帶有 + 字符的 Java 郵件 (Java mail with + character in email address)

如何快速原型化 Java 代碼? (How to quickly prototype Java code?)

如何使用 Maven 在目標(SVN-)服務器上創建 Javadoc? (How to create Javadoc on the target (SVN-) server using Maven?)

為什麼檢查二叉樹有效性的解決方案不起作用? (Why the solution for checking the validity of binary tree is not working?)

Selenium webdriver通過第一個數字找到texy (Selenium webdriver find texy by first digits)

setOnClickListener 沒有在圖像視圖上被調用 (setOnClickListener is not getting called on image view)

繪製多邊形:找不到錯誤 (Drawing Polygon : unable to find error)

半透明 JButton:對像出現在背景中 (Semi-Transparent JButton: Objects appear in Background)

比較同一數組的元素 (Compare elements of the same array)

Java 屏幕截圖小程序 (Java screen capture applet)

Minecraft 1.8.9 Forge Modding 的Java 開發工具包,需要什麼JDK/JRE,代碼是否正確? (Java Development Kit with Minecraft 1.8.9 Forge Modding, What JDK/JRE Is Needed, Is Code Correct?)

java while (resultset.next()) 不返回同一列中的所有數據 (java while (resultset.next()) does not return all data in the same column)







留言討論