Android https网络服务

时间:2015-08-19 08:39:37

标签: android json https

我想开发一个https网络服务。这时我使用http连接和json,它工作正常。这是我的代码:

    public abstract class BaseWebService
{
    public enum HttpMethod
    {
        GET, POST, PUT, PATCH, DELETE
    }

    protected static final Charset UTF8 = Charset.forName("UTF-8");

    protected static final int TIMEOUT_MILLISEC = 20000;

    protected Random random = new Random(System.currentTimeMillis());
    protected final String uri;
    protected final HttpMethod httpMethod;
    protected static Json jsonCodec;

    public int responseCode;
    public String responsePhrase;
    public Runnable afterError;
    public final HashMap<String, String> uriParams = new HashMap<String, String>();

    protected String contentType;
    protected String acceptHeader;

    static
    {
        jsonCodec = new Json(OutputType.json);
        jsonCodec.setUsePrototypes(false);
        jsonCodec.setIgnoreUnknownFields(true);
    }

    public BaseWebService(String uri, HttpMethod httpMethod)
    {
        this.uri = uri;
        this.httpMethod = httpMethod;
    }

    protected HttpParams createHttpParams()
    {
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        return httpParams;
    }

    protected HttpUriRequest createHttpRequest(AbstractHttpEntity entity) throws HttpException, UnsupportedEncodingException
    {
        HttpUriRequest httpRequest;
        String uriWithParams = getUriWithParameters();
        if (httpMethod == HttpMethod.GET)
            httpRequest = new HttpGet(uriWithParams);
        else if (httpMethod == HttpMethod.POST)
        {
            httpRequest = new HttpPost(uriWithParams);
            ((HttpPost)httpRequest).setEntity(entity);
        }
        else if (httpMethod == HttpMethod.DELETE)
            httpRequest = new HttpDelete(uriWithParams);
        else if (httpMethod == HttpMethod.PUT)
        {
            httpRequest = new HttpPut(uriWithParams);
            ((HttpPut)httpRequest).setEntity(entity);
        }
        else if(httpMethod == HttpMethod.PATCH)
        {
            httpRequest = new HttpPatch(uriWithParams);
            ((HttpPatch)httpRequest).setEntity(entity);
        }
        else
            throw new HttpException("Unsupported http method");

        if(contentType != null)
            httpRequest.setHeader("Content-Type", contentType);
        if(acceptHeader != null)
            httpRequest.setHeader("Accept", acceptHeader);
        httpRequest.setHeader("Accept-Charset", "utf-8");
        return httpRequest;
    }

    protected String executeHttpRequest(HttpUriRequest httpRequest)
    {
        HttpParams httpParams = createHttpParams();
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String responseString=null;
        try
        {
            HttpResponse response = httpClient.execute(httpRequest);
            responseCode = response.getStatusLine().getStatusCode();
            responsePhrase = response.getStatusLine().getReasonPhrase();
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity != null)
            {
                InputStream is = responseEntity.getContent();
                responseString = convertStreamToString(is);
                try
                {
                    is.close();
                } catch (Exception ignored) { }
            }
            else
                return "";
        }
        catch (IOException e)
        {
            onError(e);
        }
        return responseString;
    }

    public String getUriWithParameters() throws UnsupportedEncodingException
    {
        StringBuilder sb = new StringBuilder();
        if(uri.endsWith("/"))
            sb.append(uri.substring(0, uri.length()-1));
        else
            sb.append(uri);
        if(uriParams.isEmpty())
            return sb.toString();

        sb.append('?');
        for(String key : uriParams.keySet())
        {
            String encodedParam = URLEncoder.encode(uriParams.get(key), "UTF-8");
            sb.append(key).append('=').append(encodedParam).append('&');
        }
        sb.deleteCharAt(sb.length()-1); // delete last appended '&'
        return sb.toString();
    }

    public void onError(Exception e)
    {
        e.printStackTrace();
        if(afterError != null)
            afterError.run();
    }

    public static String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, UTF8));
        StringBuilder sb = new StringBuilder();

        String line;
        try
        {
            while ((line = reader.readLine()) != null)
                sb.append(line).append("\n");
        }
        catch (IOException e)
        {   e.printStackTrace();    }
        finally
        {
            try
            {   is.close(); }
            catch (IOException e)
            {   e.printStackTrace();    }
        }
        return sb.toString();
    }
}

现在我想将我的网络服务更改为https网络服务。我查了这篇文章https://www.npmjs.com/package/macget,但我没弄清楚。我需要在我的代码中放一个密钥吗?我怎么才能得到它?如何添加json参数?另外,我没有看到像post这样的https连接类型的任何方法。

我想了解并学习它,所以如果有人提出关于https网络服务的好的 教程 ,我会感激不尽。

0 个答案:

没有答案