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();
}
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);
}
}
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;
}
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;
}
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;
}
Aggregations