从Python到Java的POST请求重制

时间:2018-11-17 21:07:05

标签: java python apache python-requests httpclient

我需要将下一个代码从Python重新制作为Java:

import requests
import base64

def search(api_token, image):
    endpoint="https://trace.moe/api/search"
    params={"token":api_token}
    data={"image":image}
    r = requests.post(endpoint, params=params, data=data)
    if r.status_code==403:
        raise Exception("API token invalid")
    elif r.status_code==401:
        raise Exception("API token missing")
    elif r.status_code==413:
        raise Exception("The image is too large, please reduce the image size to below 1MB")
    elif r.status_code==429:
        raise Exception("You have exceeded your quota. Please wait and try again soon.")
    elif r.status_code==200:
        return(r.json())

with open("test.png", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

search = search("token", encoded_string)

我尝试将Apache HttpClient与MultipartEntity一起使用,但这并没有帮助我。

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("https://trace.moe/api/search");
File file = getImgFile();

        MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("image", cbFile);


httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

System.out.println(response.getStatusLine());
if (resEntity != null) {
    System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
    resEntity.consumeContent();
}

httpclient.getConnectionManager().shutdown();

任何尝试都给出“未收到数据”或为空的“ docs”。 我能做什么?

1 个答案:

答案 0 :(得分:0)

好的,经过几分钟的键盘敲打,我已经制作了可以使用的代码,但是它不处理请求代码,也不处理实际的JSON,您将需要实现它,它会打印出响应现在。这是您想要做的事情的基本开始。这是代码

for k,v in values_li.items():
    if k in a:
        amount = amount + v

和进口

public static void main(String[] args){
    File file = new File("C:\\Users\\Rab\\Desktop\\lol\\anime.jpg");
    try {
        byte[] fileContent = Files.readAllBytes(file.toPath());
        String imageData = Base64.getEncoder().encodeToString(fileContent);
        search("", imageData);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public static void search(String token, String image){
    try {
        String urlParameters = String.format("token=%s&image=%s", token, image);
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postData.length;
        URL url = new URL("https://trace.moe/api/search");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.addRequestProperty("charset", "utf-8");
        conn.addRequestProperty("User-Agent", "Mozilla/4.76");
        conn.addRequestProperty("Content-Length", Integer.toString(postDataLength));
        conn.setUseCaches(false);
        try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
            wr.write(postData);
        }
        InputStream inputStream = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String wtf = br.readLine();
        System.out.println(wtf);

        //Handle your data `wtf` is the response of the server


    } catch (Exception e){
        e.printStackTrace();
    }
}

旁注:anime.jpg为enter image description here