How do I translate Python urllib.request code to Java code

三世轮回 提交于 2019-12-08 05:17:30

问题


This is the python code

import urllib.request as urllib2
import json 

data =  {
    "Inputs": {
        "input1": {
            "ColumnNames": ["id", "regex"],
            "Values": [ [ "0", "the regex value" ],]
        },
    },
    "GlobalParameters": {
        "Database query": "select * from expone",
    }
}

body = str.encode(json.dumps(data))

url = 'https://ussouthcentral.services.azureml.net/workspaces/4729545551a741e1a2e606d37' \ 
      'ae61ce0/services/ac7c34ad134d43ca9fdc65e292ce35d3/execute?api-version=2.0&details=true'
api_key = '8ku5P6fR3F8ykgMHK5Y8+PL8dn+Zi2Ajmwyjk9ENsomzzkDfuT8CtgKS7dF4yjaJfYxARe+1iLjh' \ 
          'Tv1R0qOTvw=='
headers = {
    'Content-Type': 'application/json',
    'Authorization': ('Bearer '+ api_key)
}

req = urllib2.Request(url, body, headers) 

try:
    response = urllib2.urlopen(req)
    result = response.read()
    print(result) 
except Exception as e:
    print("The request failed with status code: ", e)

And this is my attempt in Java

public static void main(String[] args) {   
    System.out.println("MachineLearning main");
    try{                         
        //connections settings
        URL url = new URL("https://ussouthcentral.services.azureml.net/workspaces/4729545551a741e1a2e606d37ae61ce0/services/ac7c34ad134d43ca9fdc65e292ce35d3/execute?api-version=2.0&details=true");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);             
        String requestMethod = "GET";            
        con.setRequestMethod(requestMethod);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String data=URLEncoder.encode("input1", "UTF-8") + "="
            + URLEncoder.encode("\"ColumnNames\": [\"id\", \"regex\"]", "UTF-8") + "&" 
            + URLEncoder.encode("GlobalParameters", "UTF-8") 
            + URLEncoder.encode("Database query\": \"select * from expone\"", "UTF-8");

        //make the request
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());                
        writer.write(data);                
        writer.flush(); 

        //read the request
        BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
        String response;
        while ((response=reader.readLine())!=null) 
            System.out.println(response);        
    }
    catch(Exception e) {
        System.out.println("Exception in MachineLearning.main " + e);
    }
}

The code that is requested in java is not succesful and returns an exception: Server returned HTTP response code: 401 for URL

Problem is that I don't know how to translate the data variable in python to that in java, and how do I pass the apiKey and how is that put in the headers?


回答1:


You have several little 'bugs' in your java code :

  1. Change setRequestMethod to "POST"
  2. Change "Content-Type" to "application/json"
  3. Add a new setRequestProperty for authorization
  4. Don't urlencode the data

Code :

public static void main(String[] args) {  
    System.out.println("MachineLearning main");
    try{                         
        //connections settings
        String api_key = "8ku5P6fR3F8ykgMHK5Y8+PL8dn+Zi2Ajmwyjk9ENsomzzkDfuT8CtgKS7dF4yjaJfYxARe+1iLjhTv1R0qOTvw==";
        String data = "{\"Inputs\": {\"input1\": {\"ColumnNames\": [\"id\", \"regex\"], \"Values\": [[\"0\", \"the regex value\"]]}}, \"GlobalParameters\": {\"Database query\": \"select * from expone\"}}";
        URL url = new URL("https://ussouthcentral.services.azureml.net/workspaces/4729545551a741e1a2e606d37ae61ce0/services/ac7c34ad134d43ca9fdc65e292ce35d3/execute?api-version=2.0&details=true");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setDoInput(true);
        con.setDoOutput (true);             
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer " + api_key);

        //make the request
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());                
        writer.write(data);                
        writer.flush(); 

        //read the request
        BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
        String response;
        while ((response=reader.readLine())!=null) 
            System.out.println(response);
    } catch(Exception e) {
        System.out.println("Exception in MachineLearning.main " + e);
    }
}



回答2:


This python code up seems ok, but i tried to put it in my program code and get the message: Response code in Catch block

Is that maybe, because i need to implement WSSE auth with proper username and key or?



来源:https://stackoverflow.com/questions/43611790/how-do-i-translate-python-urllib-request-code-to-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!