Невозможно получить запрос от MSTeams на мою конечную точку - PullRequest
0 голосов
/ 23 апреля 2020

Я создал бота с помощью Bot Channels Registration и интегрировал его с каналом MSTeams. Но когда я отправлял сообщение от Команд, я не получал никаких запросов от Команд на мою конечную точку сообщения. Пожалуйста, помогите мне решить с этим. Пожалуйста, попробуйте использовать это.

    TestSample.java
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@WebServlet("/MSTeamsServlet/api/messages")
public class TestSample extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public TestSample() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream st = request.getInputStream();
        JSONObject inputjson = new JSONObject();
        JSONParser parser = new JSONParser();
        String inputJson ="";
        try {
            BufferedInputStream bin = new BufferedInputStream(st);
            int ch;
            inputJson= "";
            while ((ch = bin.read()) != -1) {
                inputJson = inputJson+(char)ch;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String result = "";
        System.out.println("INSIDE MS TEAMS SERVLET:::");
        System.out.println("REQUEST:"+inputJson);
        JSONObject json = new JSONObject();
        JSONParser parse = new JSONParser();
        JSONObject requestBody = new JSONObject();
        TestRequest client = new TestRequest();
        try
        {
            requestBody = (JSONObject)parse.parse(inputJson);
            JSONObject conversation = (JSONObject) requestBody.get("conversation");
            String id = requestBody.get("id").toString();
            String serviceUrl = requestBody.get("serviceUrl").toString();
            String conversationId = conversation.get("id").toString();
            JSONObject from = (JSONObject) requestBody.get("from");
            JSONObject recepient = (JSONObject) requestBody.get("recipient");
            String url = serviceUrl+"v3/conversations/"+conversationId+"/activities/"+id;
            String userId = "";
            String aadObjectId = from.get("aadObjectId").toString();
            json.put("text", "Hai! How can I help you!!!");
            json.put("type", "message");
            json.put("from", recepient);
            json.put("conversation", conversation);
            json.put("recipient", from);
            json.put("replyToId", id);
            result = client.hitPOSTAPI(url, "POST", json);
            System.out.println(result);
            PrintWriter out = response.getWriter();
            out.print(result);
            out.flush();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    }

TestRequest.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.Charsets;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.io.CharStreams;
public class TestRequest {
    static String microsoft_AppID = "REPLACE YOUR APP_ID";
    static String microsoft_AppPwd = "REPLACE YOUR APP_PASSWORD";
    public static String hitPOSTAPI(String urlString, String methodType, JSONObject postParameter) {
        String result = "";
        try {
            HttpPost post = new HttpPost(urlString);
            StringEntity params = new StringEntity(postParameter.toString());
            System.err.println(postParameter.toString());
            post.addHeader("content-type", "application/json");
                post.addHeader("Authorization", "Bearer "+generateToken());
            post.setEntity(params);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20 * 1000).setConnectionRequestTimeout(20*1000).setSocketTimeout(100*1000).build();
            HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
            HttpResponse response = httpClient.execute(post);
            InputStream in = null;
            if (response.getStatusLine().getStatusCode()==200 &&response != null) {
                in = response.getEntity().getContent();
                result = CharStreams.toString(new InputStreamReader(
                        in, Charsets.UTF_8));
            }
            post.abort();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
        }
        return result;
    }
    public static String generateToken() {
        String token = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        String result = "";
        try {
            url = new URL("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(5000);
            urlConnection.setRequestProperty("Host", "login.microsoftonline.com");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            OutputStream wr = urlConnection.getOutputStream();
            String credentials = "grant_type=client_credentials&client_id="+microsoft_AppID+"&client_secret="+microsoft_AppPwd+"&scope=https://api.botframework.com/.default";
            wr.write(credentials.toString().getBytes());
            wr.flush();
            wr.close();
            if(urlConnection.getResponseCode()==200)
            {
                InputStream inputStream = urlConnection.getInputStream();
                InputStreamReader isReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(isReader);
                StringBuffer sb = new StringBuffer();
                String str;
                while((str = reader.readLine())!= null){
                    sb.append(str);
                }
                JSONParser parser = new JSONParser();
                JSONObject obj = (JSONObject)parser.parse(sb.toString());
                token = obj.get("access_token").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            urlConnection.disconnect();
        }
        return token;
    }
}

Пожалуйста, проверьте, можете ли вы получить какую-либо идею. Что касается MSTeams, то только моя конечная точка не работает .. Если я проверяю ее через NGROK, она работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...