Hot questions for Using Azure in web services

Top Java Programmings / Azure / web services

Question:

I am getting 400 response code with following code:

    String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
    HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
    authConn.setRequestMethod("POST");
    authConn.setDoOutput(true);
    authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
    IOUtils.write("", authConn.getOutputStream(), "UTF-8");
    String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");

    // Using the access token to build the appid for the request url
    String appId = URLEncoder.encode("Bearer "+token, "UTF-8");
    String[] languages = {"ar","bg","ca","zh","cs", "da","nl", "fi","fr","de","el","hu", "id", "it", "ja",
            "ko","ms","no", "pl","pt","ro","ru", "es","sw","th","tr","uk","vi"};
    US_LISTING_FULL_DESCRIPTION = URLEncoder.encode(readFile("d:\\desc1.txt", Charset.defaultCharset()), "UTF-8");
    System.out.println("languages.length " + languages.length);
    WrapperBean[] wrapperBean = new WrapperBean[languages.length];
    try{

        for (int i = 0; i < languages.length; i++) {
            wrapperBean[i] = new WrapperBean();
            wrapperBean[i].setLocale(languages[i]);
            System.out.println("languages[i] " + languages[i]);
            String  url1 = String.format("https://api.microsofttranslator.com/v2/http.svc/Translate?appid=%s&text=%s&from=%s&to=%s", appId, US_LISTING_TITLE, "en", languages[i]);
            HttpsURLConnection translateConn = (HttpsURLConnection) new URL(url1).openConnection();
            translateConn.setRequestMethod("GET");
            translateConn.setRequestProperty("Accept", "application/xml");
            String translatetitle = IOUtils.toString(translateConn.getInputStream(), "UTF-8");

The last line in above code is where I get the error.

The exact error in Eclipse console is:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.microsofttranslator.com/v2/http.svc/Translate?appid=Bearer+eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY29wZSI6Imh0dHBzOi8vYXBpLm1pY3Jvc29mdHRyYW5zbGF0b3IuY29tLyIsInN1YnNjcmlwdGlvbi1pZCI6ImI0MDk0NjcwMDJkMzQ1OTVhZDljNWI3ZDA1NTcxMGNjIiwicHJvZHVjdC1pZCI6IlRleHRUcmFuc2xhdG9yLkYwIiwiY29nbml0aXZlLXNlcnZpY2VzLWVuZHBvaW50IjoiaHR0cHM6Ly9hcGkuY29nbml0aXZlLm1pY3Jvc29mdC5jb20vaW50ZXJuYWwvdjEuMC8iLCJhenVyZS1yZXNvdXJjZS1pZCI6Ii9zdWJzY3JpcHRpb25zLzExMTk0NjkyLTk1ZGEtNGU5Yi1hMDVhLTBiZjg0YTcxYzM3OC9yZXNvdXJjZUdyb3Vwcy9jc3MvcHJvdmlkZXJzL01pY3Jvc29mdC5Db2duaXRpdmVTZXJ2aWNlcy9hY2NvdW50cy9jc3MiLCJpc3MiOiJ1cm46bXMuY29nbml0aXZlc2VydmljZXMiLCJhdWQiOiJ1cm46bXMubWljcm9zb2Z0dHJhbnNsYXRvciIsImV4cCI6MTUwMTEzMDk2OX0.JPgvzprydjz5_cVi3pk23X1VxgmlqbcoL4bPADkxqYA&text=Acoustic Guitar Tuners&from=en&to=ar

The URL as such works in the browser:

Kindly help.


Answer:

HTTP status code 400 is "Bad Request". Your query is faulty. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors

The problem is AFAIK that your request contains spaces which are invalid.

&text=Acoustic Guitar Tuners&from=en&to=ar

You have to replace the spaces with for e.g. "+", like this:

&text=Acoustic+Guitar+Tuners&from=en&to=ar

See Spaces in URLs?

I hope this solves your problem. Good luck!

Question:

I did a webservice in Java EE in SCRUD. I try to put it on Azure web-app because I would like to use it for another project and it will be easier if I can put it on it. But when I deploy it on Azure, I only have acces at the index.jsp page.

My classes are like that:

@Path("LikePost")
public class LikePostAPI extends RestApplication {
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("GetAll")
public Response getAll(){
    Connection conn= GetConnection.getInstance().getConnection();
    Response response= Response.status(Response.Status.OK).entity(new DaoLikePost(conn).getAll()).build();
    return response;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("getLike")
public Response getLike(@QueryParam("id") int id) {
    Response response=null;
    Connection conn=GetConnection.getInstance().getConnection();
    Like l=new DaoLikePost(conn).find(id);
    if(l!=null)
        response=Response.status(Response.Status.OK).entity(l).build();
    else
        response=Response.status(Response.Status.NO_CONTENT).entity(null).build();
    return response;
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("CreateLike")
public Response createLike(@FormParam("dateLiked") String dateLike,@FormParam("user") String userId,@FormParam("post") String postId){
    Connection conn=GetConnection.getInstance().getConnection();
    Like l=new Like();
    l.setUser(new DaoUser(conn).find(Integer.parseInt(userId)));
    DateFormat dateFormat=new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    Date date=null;
    try {
        date=dateFormat.parse(dateLike);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    l.setDateLiked(date);
    l.setPost(new DaoPost(conn).find(Integer.parseInt(postId)));
    Boolean test=new DaoLikePost(conn).create(l);
    Response response=null;
    if(test)
        response=Response.status(Response.Status.OK).entity(test).build();
    else
        response=Response.status(Response.Status.BAD_REQUEST).entity(test).build();
    return response;
}
@DELETE
@Path("DeleteLike")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteLike(@QueryParam("id")int id){
    Connection conn=GetConnection.getInstance().getConnection();
    Like l=new DaoLikePost(conn).find(id);
    Boolean test=new DaoLikePost(conn).delete(l);
    Response response=null;
    if(test)
        response=Response.status(Response.Status.OK).entity(test).build();
    else
        response=Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(null).build();
    return response;
}
@PUT
@Path("UpdateLike")
@Produces(MediaType.APPLICATION_JSON)
public Response updateLike(@FormParam("id") String idLike,@FormParam("dateLiked") String dateLike,@FormParam("user") String userId,@FormParam("post") String postId){
    Connection conn=GetConnection.getInstance().getConnection();
    Like l=new Like();
    l.setId(Integer.parseInt(idLike));
    l.setUser(new DaoUser(conn).find(Integer.parseInt(userId)));
    Date date=null;
    DateFormat dateFormat=new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    try {
        date=dateFormat.parse(dateLike);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    l.setDateLiked(date);
    l.setPost(new DaoPost(conn).find(Integer.parseInt(postId)));
    Boolean test=new DaoLikePost(conn).update(l);
    Response response=null;
    if(test)
        response=Response.status(Response.Status.OK).entity(test).build();
    else
        response=Response.status(Response.Status.BAD_REQUEST).entity(null).build();
    return response;
}
}

here's the configuration for the deployement: https://gyazo.com/fed4d79d5d3cb72a820073efd234feb2

for the artifacts exploded: https://gyazo.com/a948f72cff3b89fd86df7d820aa928eb

and for the war file: https://gyazo.com/7ac6ead33bd6a129a4ad2a7ec537acd0

The Azure website is: https://faceapibook.azurewebsites.net/


Answer:

First of all, without Azure using IntelliJ, you have to make sure your application will be running normally in Tomcat or Jetty on your local machine.

Then you can follow the two offical tutorials below to directly deploy it to Azure in your IntelliJ with Azure Toolkit plugin.

  1. Create a Hello World web app for Azure using IntelliJ
  2. Publish a Spring Boot app as a Docker container by using the Azure Toolkit for IntelliJ

Besides, if you can make your exported war file works in your local tomcat server, you also can follow the section Deploy WAR file of the offical document Deploy your app to Azure App Service with a ZIP or WAR file to deploy the war file exported from your IntelliJ project, and see more details from the wiki page Deploying WAR files using wardeploy.

Even, when you correctly set the value of Java version in the tab Application settings of Azure portal, as below, you can upload the war file into the webapps directory under the path wwwroot of Kudo console directly to complete the deployment.

Question:

I am trying to develop a client program that creates a device identity thanks to azure . im using azure rest to create it so i call this webservice from client programme using jersey implementation but i get error com.sun.jersey.api.client.ClientHandlerException: java.net.SocketException: Socket is not connected: connect i test it using postman it work and python it work to . here is my java code :

public class Test {

    public static void main(String[] args) {

        try {

            Client client = Client.create();

            WebResource webResource = client
                    .resource("https://xxxx-iot-hub.azure-devices.net/devices");

            ClientResponse response =     webResource.path("/iotdevice1").queryParam("top", "100").queryParam("api-version", "2016-02-03").header("Content-Type", "application/json")
                    .header("Authorization", "SharedAccessSignature sr=xxxxx-iot-hub.azure-devices.net&sig=Yxxxxxxxxxx=1497357420&skn=iothubowner")
                    .put(ClientResponse.class);



            String output = response.getEntity(String.class);

            System.out.println("Output from Server .... \n");
            System.out.println(output);

        } catch (Exception e) {

            e.printStackTrace();

        }
    }

}

Thanks


Answer:

According to your code, it seems that you want to create a new device identity using the REST API with HTTP PUT Method.

However, in your code, the query parameter top=100 is not necessary and the request body {deviceId: "iotdevice1"} is missing.

Here is my working code.

String body = "{deviceId: \"iotdevices1\"}";
ClientResponse response = webResource.path("/iotdevices1").queryParam("api-version", "2016-02-03")
                    .header("Content-Type", "application/json")
                    .header("Authorization",
                            "SharedAccessSignature sr=xxxx.azure-devices.net&sig=xxxxxxxx&se=1497357420&skn=iothubowner")
                    .put(ClientResponse.class, body);

Hope it helps. Any concern, please feel free to let me know.


Update:

For deleting a existing device identity, please see the REST API reference and see the code below.

ClientResponse response = webResource.path("/iotdevices1").queryParam("api-version", "2016-02-03")
                    .header("Content-Type", "application/json")
                    .header("If-Match", "*")
                    .header("Authorization",
                            "SharedAccessSignature sr=xxxx.azure-devices.net&sig=xxxxxx&se=1497490976&skn=iothubowner")
                    .delete(ClientResponse.class);

Please take note of the header If-Match above.