Android 调用百度识图工具

最近对百度的炮轰不断,我却要写一个跟百度相关的应用工具,简直毫无违和感。不过,秉承着技术无罪的崇高理念,我还是说一些我的实现过程。
最近帮一个朋友写一个Android图像处理的应用,我主要实现功能是调用百度识图对图片进行识别,并从网页提取到返回结果。功能其实很简单,可怜百度公司并没有提供百度识图的API,导致智能通过模拟网页请求的方式实现。
当然在实现的过程中参考了很多大神的博客,然而都被我消化道代码中了,在此不一一列出了。实现的功能主要是:给定图片的路径,可以直接上传文件获取;如果是网络图片,需要给定图片链接。话不多说,直接上代码。

package com.example.baidushitutest;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.util.Log;

public class ShituUtils {
    private static final String TAG = "ShituUtils";
    private static final int TIME_OUT = 10 * 1000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码
    public static String resolvePostResponse(String postResponseUrl){
        String requestUri = "http://image.baidu.com" + postResponseUrl;
        HttpGet httpRequest = new HttpGet(requestUri);
        String strResult = null;
        try {

            HttpResponse httpResponse = new DefaultHttpClient()
                    .execute(httpRequest);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {

                strResult = EntityUtils.toString(httpResponse
                        .getEntity());

                Document document = Jsoup.parseBodyFragment(strResult);
                strResult = document.getElementsByClass("guess-info-not-found-title").text();
                if (strResult == ""){
                    strResult = document.getElementsByClass("guess-info-text").text();
                    if(strResult == ""){
                        strResult = document.getElementsByClass("error-msg").text();
                    }
                }
                return strResult;
            } else {
                strResult = "Error Response";
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strResult;
    }

    public static String postFile(String filePath, String requestURL) {
        int res=0;
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型
        File file = new File(filePath);
        try {

            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setChunkedStreamingMode(1024 * 1024);// 1024K  
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="+ BOUNDARY);
            if (file != null) {
                /**
                 * 当文件不为空时执行上传
                 */
                OutputStream outputSteam=conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);

                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字,包含后缀名
                 */

                sb.append("Content-Disposition: form-data; name=\"filedata\"; filename=\""
                        + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="
                        + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);

                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                        .getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功 当响应成功,获取响应的流
                 */

                res = conn.getResponseCode();

                Log.e(TAG, "response code:" + res);
                if (res == 200) {
                    Log.e(TAG, "request success");
                    InputStream input = conn.getInputStream();
                    StringBuffer sb1 = new StringBuffer();
                    int ss;
                    while ((ss = input.read()) != -1) {
                        sb1.append((char) ss);
                    }
                    result = sb1.toString();
                    Log.e(TAG, "result : " + result);
                } else {
                    Log.e(TAG, "request error");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static String baiduShitu(String imageUrl){
        String uriAPI = null;
        try {
            uriAPI = "http://image.baidu.com/n/pc_search?queryImageUrl="+URLEncoder.encode(imageUrl,"utf-8")+"&fm=result&pos=&uptype=paste";
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        HttpGet httpRequest = new HttpGet(uriAPI);
        String strResult = null;
        try {

            HttpResponse httpResponse = new DefaultHttpClient()
                    .execute(httpRequest);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {

                strResult = EntityUtils.toString(httpResponse
                        .getEntity());

                Document document = Jsoup.parseBodyFragment(strResult);
                strResult = document.getElementsByClass("guess-info-not-found-title").text();
                if (strResult == ""){
                    strResult = document.getElementsByClass("guess-info-text").text();
                    if(strResult == ""){
                        strResult = document.getElementsByClass("error-msg").text();
                    }
                }
                return strResult;
            } else {
                strResult = "Error Response";
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strResult;
    }
}

提取网页内容用的工具jsoup,可以从网上下载。这里是实现的一个demo

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值