Search in sources :

Example 61 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project weixin-java-tools by chanjarster.

the class WxMpServiceImpl method getAccessToken.

public String getAccessToken(boolean forceRefresh) throws WxErrorException {
    if (forceRefresh) {
        wxMpConfigStorage.expireAccessToken();
    }
    if (wxMpConfigStorage.isAccessTokenExpired()) {
        synchronized (globalAccessTokenRefreshLock) {
            if (wxMpConfigStorage.isAccessTokenExpired()) {
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + wxMpConfigStorage.getAppId() + "&secret=" + wxMpConfigStorage.getSecret();
                try {
                    HttpGet httpGet = new HttpGet(url);
                    if (httpProxy != null) {
                        RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
                        httpGet.setConfig(config);
                    }
                    CloseableHttpResponse response = getHttpclient().execute(httpGet);
                    String resultContent = new BasicResponseHandler().handleResponse(response);
                    WxError error = WxError.fromJson(resultContent);
                    if (error.getErrorCode() != 0) {
                        throw new WxErrorException(error);
                    }
                    WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
                    wxMpConfigStorage.updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
                } catch (ClientProtocolException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    return wxMpConfigStorage.getAccessToken();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) WxError(me.chanjar.weixin.common.bean.result.WxError) WxAccessToken(me.chanjar.weixin.common.bean.WxAccessToken) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) IOException(java.io.IOException) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 62 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project weixin-java-tools by chanjarster.

the class WxMpServiceImpl method executeInternal.

protected synchronized <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException {
    if (uri.indexOf("access_token=") != -1) {
        throw new IllegalArgumentException("uri参数中不允许有access_token: " + uri);
    }
    String accessToken = getAccessToken(false);
    String uriWithAccessToken = uri;
    uriWithAccessToken += uri.indexOf('?') == -1 ? "?access_token=" + accessToken : "&access_token=" + accessToken;
    try {
        return executor.execute(getHttpclient(), httpProxy, uriWithAccessToken, data);
    } catch (WxErrorException e) {
        WxError error = e.getError();
        /*
       * 发生以下情况时尝试刷新access_token
       * 40001 获取access_token时AppSecret错误,或者access_token无效
       * 42001 access_token超时
       */
        if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001) {
            // 强制设置wxMpConfigStorage它的access token过期了,这样在下一次请求里就会刷新access token
            wxMpConfigStorage.expireAccessToken();
            return execute(executor, uri, data);
        }
        if (error.getErrorCode() != 0) {
            throw new WxErrorException(error);
        }
        return null;
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : WxError(me.chanjar.weixin.common.bean.result.WxError) IOException(java.io.IOException) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 63 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project carat by amplab.

the class JsonParser method getJSONFromUrl.

public String getJSONFromUrl(String url) {
    InputStream inputStream = null;
    String result = null;
    ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
    try {
        // Set up HTTP post
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(param));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        // Read content & Log
        inputStream = httpEntity.getContent();
    } catch (UnknownHostException e0) {
        Log.d("JsonParser", "Unable to connect to the statstics server (no Internet on the device! is Wifi or mobile data on?), " + e0.toString());
        return "";
    } catch (UnsupportedEncodingException e1) {
        Log.e("UnsupportedEncodingException", e1.toString());
        return "";
    } catch (ClientProtocolException e2) {
        Log.e("ClientProtocolException", e2.toString());
        return "";
    } catch (IllegalStateException e3) {
        Log.e("IllegalStateException", e3.toString());
        return "";
    } catch (IOException e4) {
        Log.e("IOException", e4.toString());
        return "";
    }
    // Convert response to string using String Builder
    try {
        BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
        StringBuilder sBuilder = new StringBuilder();
        String line = null;
        while ((line = bReader.readLine()) != null) {
            sBuilder.append(line + "\n");
        }
        inputStream.close();
        result = sBuilder.toString();
    } catch (Exception e) {
        Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
    }
    return result;
}
Also used : NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) UnknownHostException(java.net.UnknownHostException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader)

Example 64 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project DrupalCloud by INsReady.

the class JSONServerClient method call.

/**
	 * Generic request
	 * 
	 * @param method
	 *            Request name
	 * @param parameters
	 *            Parameters
	 * @return result string
	 */
public String call(String method, BasicNameValuePair[] parameters) throws ServiceNotAvailableException {
    String sessid = this.getSessionID();
    mPairs.clear();
    String nonce = Integer.toString(new Random().nextInt());
    Mac hmac;
    try {
        hmac = Mac.getInstance(JSONServerClient.mALGORITHM);
        final Long timestamp = new Date().getTime() / 100;
        final String time = timestamp.toString();
        hmac.init(new SecretKeySpec(JSONServerClient.mAPI_KEY.getBytes(), JSONServerClient.mALGORITHM));
        String message = time + ";" + JSONServerClient.mDOMAIN + ";" + nonce + ";" + method;
        hmac.update(message.getBytes());
        String hmac_value = new String(Hex.encodeHex(hmac.doFinal()));
        mPairs.add(new BasicNameValuePair("hash", hmac_value));
        mPairs.add(new BasicNameValuePair("domain_name", JSONServerClient.mDOMAIN));
        mPairs.add(new BasicNameValuePair("domain_time_stamp", time));
        mPairs.add(new BasicNameValuePair("nonce", nonce));
        mPairs.add(new BasicNameValuePair("method", method));
        mPairs.add(new BasicNameValuePair("api_key", JSONServerClient.mAPI_KEY));
        mPairs.add(new BasicNameValuePair("sessid", sessid));
        for (int i = 0; i < parameters.length; i++) {
            mPairs.add(parameters[i]);
        }
        mSERVER.setEntity(new UrlEncodedFormEntity(mPairs));
        HttpResponse response = mClient.execute(mSERVER);
        InputStream is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String result = br.readLine();
        JSONObject jso;
        jso = new JSONObject(result);
        boolean error = jso.getBoolean("#error");
        if (error) {
            String errorMsg = jso.getString("#data");
            throw new ServiceNotAvailableException(this, errorMsg);
        }
        return result;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
        throw new ServiceNotAvailableException("Remote server is not available");
    }
    return null;
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) Mac(javax.crypto.Mac) Date(java.util.Date) ClientProtocolException(org.apache.http.client.ClientProtocolException) Random(java.util.Random) JSONObject(org.json.JSONObject) SecretKeySpec(javax.crypto.spec.SecretKeySpec) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BufferedReader(java.io.BufferedReader)

Example 65 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project openhab1-addons by openhab.

the class Tr064Comm method readSoapResponse.

/***
     *
     * @param soapActionHeader String in HTTP Header. specific for each TR064 service
     * @param request the SOAPMEssage Object to send to fbox as request
     * @param serviceUrl URL to sent the SOAP Message to (service specific)
     * @return
     */
private SOAPMessage readSoapResponse(String soapActionHeader, SOAPMessage request, String serviceUrl) {
    SOAPMessage response = null;
    // Soap Body to post
    // url is service specific
    HttpPost postSoap = new HttpPost(serviceUrl);
    // add the Header specific for this request
    postSoap.addHeader("SOAPAction", soapActionHeader);
    HttpEntity entBody = null;
    // stores raw response from fbox
    HttpResponse resp = null;
    boolean exceptionOccurred = false;
    try {
        // add body
        entBody = new StringEntity(soapToString(request), ContentType.create("text/xml", "UTF-8"));
        postSoap.setEntity(entBody);
        resp = _httpClient.execute(postSoap, _httpClientContext);
        // Fetch content data
        StatusLine slResponse = resp.getStatusLine();
        HttpEntity heResponse = resp.getEntity();
        // Check for (auth-) error
        if (slResponse.getStatusCode() == 401) {
            logger.error("Could not read response from FritzBox. Unauthorized! Check User/PW in config. Create user for tr064 requests");
            return null;
        }
        // Parse response into SOAP Message
        response = MessageFactory.newInstance().createMessage(null, heResponse.getContent());
    } catch (UnsupportedEncodingException e) {
        logger.error("Encoding not supported: {}", e.getMessage().toString());
        response = null;
        exceptionOccurred = true;
    } catch (ClientProtocolException e) {
        logger.error("Client Protocol not supported: {}", e.getMessage().toString());
        response = null;
        exceptionOccurred = true;
    } catch (IOException e) {
        logger.error("Cannot send/receive: {}", e.getMessage().toString());
        response = null;
        exceptionOccurred = true;
    } catch (UnsupportedOperationException e) {
        logger.error("Operation unsupported: {}", e.getMessage().toString());
        response = null;
        exceptionOccurred = true;
    } catch (SOAPException e) {
        logger.error("SOAP Error: {}", e.getMessage().toString());
        response = null;
        exceptionOccurred = true;
    } finally {
        // Make sure connection is released. If error occurred make sure to print in log
        if (exceptionOccurred) {
            logger.error("Releasing connection to FritzBox because of error!");
        } else {
            logger.debug("Releasing connection");
        }
        postSoap.releaseConnection();
    }
    return response;
}
Also used : StatusLine(org.apache.http.StatusLine) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) HttpEntity(org.apache.http.HttpEntity) SOAPException(javax.xml.soap.SOAPException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) SOAPMessage(javax.xml.soap.SOAPMessage) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Aggregations

ClientProtocolException (org.apache.http.client.ClientProtocolException)92 IOException (java.io.IOException)80 HttpResponse (org.apache.http.HttpResponse)49 HttpPost (org.apache.http.client.methods.HttpPost)37 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)30 HttpClient (org.apache.http.client.HttpClient)29 HttpGet (org.apache.http.client.methods.HttpGet)25 HttpEntity (org.apache.http.HttpEntity)23 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)20 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)19 InputStreamReader (java.io.InputStreamReader)18 ArrayList (java.util.ArrayList)18 UnsupportedEncodingException (java.io.UnsupportedEncodingException)17 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 BufferedReader (java.io.BufferedReader)13 InputStream (java.io.InputStream)13 NameValuePair (org.apache.http.NameValuePair)13 StringEntity (org.apache.http.entity.StringEntity)12 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)11 URI (java.net.URI)10