这是我的代码:
public class HttpClient {
public String AddressBase = "";
String _AccessToken = "";
String _AccessToken = "";
public HttpClient() {
}
public HttpClient(String accessToken) {
_AccessToken = accessToken;
}
private HttpURLConnection _CreateConnection(String url, final ArrayList<Pair<String, String>> params) throws IOException {
Uri.Builder uriB1 = Uri.parse(AddressBase).buildUpon()
.appendEncodedPath(url);
if (params != null)
for (Pair<String, String> p :
params) {
uriB1 = uriB1.appendQueryParameter(p.first, p.second);
}
URL callUrl = new URL(uriB1.build().toString());
HttpURLConnection connection = (HttpURLConnection) callUrl.openConnection();
if (!_AccessToken.isEmpty())
connection.setRequestProperty("Authorization", "Bearer " + _AccessToken);
return connection;
}
private <T, Y> Y _Post(final String url, final ArrayList<Pair<String, String>> params, final T object, final Class<Y> objectClass) {
Log.e("check net", "_post");
return _Post(url, params, AppConstants.Gson_Get().toJson(object), "application/json", objectClass);
}
private <Y> Y _Post(final String url, final ArrayList<Pair<String, String>> params, final String postBodyContent, String postBodyContentType, final Class<Y> objectClass) {
Y r = null;
HttpURLConnection connection = null;
try {
Log.e("tag", " try create connection");
connection = _CreateConnection(url, params);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-type", postBodyContentType);
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
if (postBodyContent != null && !postBodyContent.isEmpty()) {
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
wr.write(postBodyContent);
wr.flush();
}
connection.connect();
Log.e("tag", " connection connected");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
String h1 = connection.getHeaderField("Content-Encoding");
if (h1 != null && h1.equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = _ConvertStreamToString(inputStream);
inputStream.close();
r = AppConstants.Gson_Get().fromJson(resultString, objectClass);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
private String _ConvertStreamToString(InputStream inputStream) {
Log.e("checknet", "cnovert stram to string");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return stringBuilder.toString();
}
public <T, Y> Y Post(final String url, final T object, final Class<Y> objectClass) {
return _Post(url, null, object, objectClass);
}
public <T> T PostParamsInQuery(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
return _Post(url, params, null, "application/json", objectClass);
}
public <T> T PostParamsInBody(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
StringBuilder postBodyContent = new StringBuilder("");
for (Pair<String, String> p :
params) {
try {
if (postBodyContent.length() != 0)
postBodyContent.append('&');
postBodyContent.append(URLEncoder.encode(p.first, "UTF-8"));
postBodyContent.append("=");
postBodyContent.append(URLEncoder.encode(p.second, "UTF-8"));
} catch (Exception e) {
}
}
return _Post(url, null, postBodyContent.toString(), "application/x-www-form-urlencoded", objectClass);
}
public <T> T Get(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
T r = null;
HttpURLConnection connection = null;
try {
connection = _CreateConnection(url, params);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
if (connection.getHeaderField("Content-Encoding").equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = _ConvertStreamToString(inputStream);
inputStream.close();
r = AppConstants.Gson_Get().fromJson(resultString, objectClass);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
public boolean Delete(String url, final ArrayList<Pair<String, String>> params) {
boolean r = false;
HttpURLConnection connection = null;
try {
connection = _CreateConnection(url, params);
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.connect();
r = connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT;
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
public <T, Y> Y InvokeApi(String apiName, final T arg, Class<Y> returnClass) {
return Post(String.format("/api/%s", apiName), arg, returnClass);
}
public <T, Y> void InvokeApiAsync(final String apiName, final T arg, final Class<Y> returnClass, final ActionListener<Y> listener) {
new AsyncTask<Void, Void, Y>() {
@Override
protected Y doInBackground(Void... params) {
return InvokeApi(apiName, arg, returnClass);
}
@Override
protected void onPostExecute(Y result) {
if (listener != null) {
listener.Action(result);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
当我调用InvokeApiAsync
时,由于.getoutputstream(),需要很长时间才能得到响应3分钟。我一直在使用AsyncTask进行并行连接。我不知道该怎么办我会感激任何帮助。
答案 0 :(得分:0)
之前我遇到过这个问题,请检查您的设备上的网络(可能是WiFi)代理,然后测试您的代码!
Android尝试连接到代理,如果失败(代理不正确或代理速度很慢),它会等待很长时间(默认)来获取outputStream。
关闭代理或将超时设置为较小的值以更快获得超时异常!
答案 1 :(得分:0)
最好使用IntentService而不是AsyncTask进行API连接。