REST-API
love-dev.1988 Aug 13, 2014 10:25 AMHi Experts;
I'm trying to complete a task in kie-wb using eclipse, I'm based on REST-API.
I added the class rest.java to my project:
- package com.acme.rewards.ejb;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.Writer;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- public class rest {
- public static String httpGet(String urlStr) throws IOException {
- URL url = new URL(urlStr);
- HttpURLConnection conn =(HttpURLConnection) url.openConnection();
- System.out.println(conn.getResponseCode());
- if (conn.getResponseCode() != 200) {
- throw new IOException(conn.getResponseMessage());
- }
- BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = rd.readLine()) != null) {
- sb.append(line);
- }
- rd.close();
- conn.disconnect();
- return sb.toString();
- }
- public static String httpPost(String urlStr, String[] paramName,
- String[] paramVal) throws Exception {
- URL url = new URL(urlStr);
- HttpURLConnection conn =(HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
- conn.setDoInput(true);
- conn.setUseCaches(false);
- conn.setAllowUserInteraction(false);
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- // Create the form content
- OutputStream out = conn.getOutputStream();
- Writer writer = new OutputStreamWriter(out, "UTF-8");
- for (int i = 0; i < paramName.length; i++) {
- writer.write(paramName[i]);
- writer.write("=");
- writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
- writer.write("&");
- }
- writer.close();
- out.close();
- if (conn.getResponseCode() != 200) {
- throw new IOException(conn.getResponseMessage());
- }
- BufferedReader rd = new BufferedReader(
- new InputStreamReader(conn.getInputStream()));
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = rd.readLine()) != null) {
- sb.append(line);
- }
- rd.close();
- conn.disconnect();
- return sb.toString();
- }
- public static void main(String[] args) {
- String urlStr="http://localhost:8080/jbpm-console/rest/task/778";
- try {
- httpGet(urlStr);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
When I http://localhost:8080/jbpm-console/rest/task/778 on the browser, I obtained the file XML: So it's well.
The problem is :Once I run as java Application, I obtained this error:
- 401
- java.io.IOException: Unauthorized
- at com.acme.rewards.ejb.rest.httpGet(rest.java:23)
- at com.acme.rewards.ejb.rest.main(rest.java:91)
Could you please help me solving this error ?
Thanks in advance.