Search in sources :

Example 6 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project Notes by MiCode.

the class GTaskClient method getTaskLists.

public JSONArray getTaskLists() throws NetworkFailureException {
    if (!mLoggedin) {
        Log.e(TAG, "please login first");
        throw new ActionFailureException("not logged in");
    }
    try {
        HttpGet httpGet = new HttpGet(mGetUrl);
        HttpResponse response = null;
        response = mHttpClient.execute(httpGet);
        // get the task list
        String resString = getResponseContent(response.getEntity());
        String jsBegin = "_setup(";
        String jsEnd = ")}</script>";
        int begin = resString.indexOf(jsBegin);
        int end = resString.lastIndexOf(jsEnd);
        String jsString = null;
        if (begin != -1 && end != -1 && begin < end) {
            jsString = resString.substring(begin + jsBegin.length(), end);
        }
        JSONObject js = new JSONObject(jsString);
        return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
    } catch (ClientProtocolException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new NetworkFailureException("gettasklists: httpget failed");
    } catch (IOException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new NetworkFailureException("gettasklists: httpget failed");
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new ActionFailureException("get task lists: handing jasonobject failed");
    }
}
Also used : ActionFailureException(net.micode.notes.gtask.exception.ActionFailureException) JSONObject(org.json.JSONObject) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) NetworkFailureException(net.micode.notes.gtask.exception.NetworkFailureException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 7 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project Notes by MiCode.

the class GTaskClient method postRequest.

private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
    if (!mLoggedin) {
        Log.e(TAG, "please login first");
        throw new ActionFailureException("not logged in");
    }
    HttpPost httpPost = createHttpPost();
    try {
        LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
        list.add(new BasicNameValuePair("r", js.toString()));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
        httpPost.setEntity(entity);
        // execute the post
        HttpResponse response = mHttpClient.execute(httpPost);
        String jsString = getResponseContent(response.getEntity());
        return new JSONObject(jsString);
    } catch (ClientProtocolException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new NetworkFailureException("postRequest failed");
    } catch (IOException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new NetworkFailureException("postRequest failed");
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new ActionFailureException("unable to convert response content to jsonobject");
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new ActionFailureException("error occurs when posting request");
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ActionFailureException(net.micode.notes.gtask.exception.ActionFailureException) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) LinkedList(java.util.LinkedList) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONException(org.json.JSONException) NetworkFailureException(net.micode.notes.gtask.exception.NetworkFailureException) IOException(java.io.IOException) ActionFailureException(net.micode.notes.gtask.exception.ActionFailureException) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NetworkFailureException(net.micode.notes.gtask.exception.NetworkFailureException)

Example 8 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project SmartAndroidSource by jaychou2012.

the class AbstractAjaxCallback method httpDo.

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException {
    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }
    }
    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }
    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, hr);
    }
    DefaultHttpClient client = getClient();
    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }
    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    request = hr;
    if (abort) {
        throw new IOException("Aborted");
    }
    HttpResponse response = client.execute(hr, context);
    byte[] data = null;
    String redirect = url;
    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;
    HttpEntity entity = response.getEntity();
    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);
    File file = null;
    if (code < 200 || code >= 300) {
        try {
            if (entity != null) {
                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);
                error = new String(s, "UTF-8");
                AQUtility.debug("error", error);
            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }
    } else {
        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();
        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
        OutputStream os = null;
        InputStream is = null;
        try {
            file = getPreFile();
            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }
            //AQUtility.time("copy");
            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());
            //AQUtility.timeEnd("copy", 0);
            os.flush();
            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }
        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file).client(client).context(context).headers(response.getAllHeaders());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) BufferedOutputStream(java.io.BufferedOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 9 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project FastDev4Android by jiangqqlmj.

the class IoUtils method getInputStreamFromUrl.

public static InputStream getInputStreamFromUrl(String url, RequestCallBack requestCallBack) {
    if (url == null || !url.contains("http://")) {
        Log.e("listlogic", "列表下载地址异常");
        return null;
    }
    if (requestCallBack != null) {
        requestCallBack.onRequestStart();
    }
    if (requestCallBack != null) {
        requestCallBack.onRequestLoading();
    }
    URI encodedUri = null;
    HttpGet httpGet = null;
    try {
        encodedUri = new URI(url);
        httpGet = new HttpGet(encodedUri);
    } catch (URISyntaxException e) {
        // 清理一些空格
        String encodedUrl = url.replace(' ', '+');
        httpGet = new HttpGet(encodedUrl);
        e.printStackTrace();
    }
    // 创建httpclient对象
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEF_CONN_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEF_SOCKET_TIMEOUT);
    HttpResponse httpResponse = null;
    InputStream inputStream = null;
    try {
        try {
            // 执行请求
            httpResponse = httpClient.execute(httpGet);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        if (httpResponse != null) {
            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpStatus.SC_OK) {
                // 请求数据
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    inputStream = httpEntity.getContent();
                    byte[] bytes = getByteArrayFromInputstream(inputStream);
                    if (bytes != null) {
                        InputStream inputStream2 = new ByteArrayInputStream(bytes);
                        if (requestCallBack != null) {
                            requestCallBack.onRequestSuccess(inputStream2);
                        }
                        return inputStream2;
                    }
                }
            } else {
                httpGet.abort();
                if (requestCallBack != null) {
                    requestCallBack.onRequestError(RequestCallBack.HTTPSTATUSERROR, "HTTP链接错误");
                }
            }
        } else {
            httpGet.abort();
            if (requestCallBack != null) {
                requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
        }
    } catch (IOException e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
        }
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (requestCallBack != null) {
            requestCallBack.onCancel();
        }
    }
    return null;
}
Also used : SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DataInputStream(java.io.DataInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient)

Example 10 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project Klyph by jonathangerbaud.

the class HttpRequest2 method send.

public String send() {
    client = AndroidHttpClient.newInstance("Android");
    HttpPost request = new HttpPost(url);
    if (params != null) {
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
            entity.setContentEncoding(HTTP.UTF_8);
            request.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            Log.e("", "UnsupportedEncodingException: " + e);
        }
    }
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String response = "";
    try {
        response = client.execute(request, responseHandler);
    } catch (ClientProtocolException e) {
        Log.e("HttpRequest2", e.toString());
    } catch (IOException e) {
        Log.e("HttpRequest2", e.toString());
    }
    if (LOG_RESPONSE == true)
        Log.i("HttpRequest2", response);
    if (HTML_TRANSFORM == true)
        response = Html.fromHtml(response).toString();
    close();
    return response;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) ArrayList(java.util.ArrayList) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ClientProtocolException (org.apache.http.client.ClientProtocolException)83 IOException (java.io.IOException)75 HttpResponse (org.apache.http.HttpResponse)45 HttpPost (org.apache.http.client.methods.HttpPost)33 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)29 HttpClient (org.apache.http.client.HttpClient)28 HttpGet (org.apache.http.client.methods.HttpGet)24 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)20 HttpEntity (org.apache.http.HttpEntity)19 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)19 ArrayList (java.util.ArrayList)18 UnsupportedEncodingException (java.io.UnsupportedEncodingException)17 InputStreamReader (java.io.InputStreamReader)14 NameValuePair (org.apache.http.NameValuePair)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 InputStream (java.io.InputStream)12 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)11 BufferedReader (java.io.BufferedReader)9 StringEntity (org.apache.http.entity.StringEntity)9 JSONException (org.json.JSONException)9